I have an issue with Python/Django where I have either a String or a List of Strings being passed to a Template. If it is a list I need to iterate through it and output each String on a separate line, and if it is a String I just need to output the string. I need to be able to differentiate between the value types and adjust accordingly.
Currently I have code similiar to this:
if isinstance(values, list):
for value in values:
html += value + "<br />"
else:
html += values + "<br />"
My problem is twofold:
Firstly, I am looking for a better/more pythonic way (if possible) to do this which will have the same result. I know that for some situations the isinstance
method is not an ideal solution, but would I be able to utilize something like hasattr
and would it be an improvement in terms of efficiency?
Secondly, I would ideally want this to be implemented using the Django Template language. If I continue using isinstance
or change to hasattr
I would have to either make a custom Template filter or tag to be able to pass the proper arguments. Should I forget the template and just write a the code that generates HTML in the view (bad practice) or would the answers to one of these be the best approach for my situation? (Performing a getattr() style lookup in a django template or django template system, calling a function inside a model)
The current template code can be found here: http://pastebin.com/JK2PRrWv
Background:
I am currently working on some Python(Django) code that implements a simple REST/Json API used to handle queries. One of the requirements is to convert a list of Python dictionaries(parsed from JSON) into very simple HTML tables. To implement this functionality, I have utilized a Django template that takes the list of Python dictionaries and generates HTML from it.
Any help/constructive criticism would be greatly appreciated.