How can I distinguish lists from strings in django templates
I'm developing a project on Google AppEngine, using Django templates, so I have to use tags like {{ aitem.Author }}
to print content within my HTML template.
Author
, however, can either be a string or a list object, and I have no way to tell it in advance. When the Author is a 开发者_运维技巧list and I try to print it on my template, I get the ugly result of
Author: [u'J. K. Rowling', u'Mary GrandPr\xe9']
Is there any way to handle this kind of scenario (basically printing a field differently depending on its type) effectively? Do I have to rely on custom tags or any other means?
I think the cleanest solution would be to add a method to the model get_authors()
which always returns a list either of one or more authors. Then you can use:
Author: {{ aitem.get_authors|join:", " }}
If you for some reason have only access to the templates and can't change the model, then you can use a hack like this:
{% if "[" == aitem.Author|pprint|slice:":1" %}
Author: {{ aitem.Author|join:", " }}
{% else %}
Author: {{ aitem.Author }}
{% endif %}
P.S. it's not a good convention to use capital letters for attribute names.
I think that Aidas's get_authors()
solution is the best, but an alternative might be to create a template tag that does the test. You'll want to read up on custom template tags, but they aren't that hard to create if you look at the existing ones.
I followed Matthew's advice and eventually implemented a filter to handle lists. I'm posting it here just in case someone else needs it.
@register.filter(name='fixlist')
def fixlist(author):
if type(author) == list:
return ', '.join(author)
else:
return author
I call it from the template pages like this {{ aitem.Author|fixlist }}
Thank you for the help!
精彩评论