views:

62

answers:

3

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?

+5  A: 

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.

Aidas Bendoraitis
You're right, but unfortunately I'm not able to modify the model for that: I'm using a library and can't easily change that thing. That explains the ill-named properties, too.
abahgat
Instead of `pprint`, isn't better to check for a type specific method? E.g. `if author.islower` only evaluates true if string.
Török Gábor
Nice idea. I haven't thought about that.
Aidas Bendoraitis
+1  A: 

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.

Matthew Schinckel
A: 

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!

abahgat