tewok tewok - 18 days ago 6
Python Question

How to tell list from non-list in Django template?

I've got a Django template I'd sometimes like to pass a list and sometimes like to pass a single value. How can the template tell which it was given?

I'm thinking the value would be set like one of these:

context = {
'foo' : 'bar
}


or:

context = {
'foo' : ['bar', 'bat', 'baz']
}


Then, the template would have code that looks something like this:

{% if foo isa list %}
{% for item in foo %}
{{ item }}<br>
{% endfor %}
{% else %}
{{ item}}<br>
{% endif %}


I can set it up to have foo or foolist, for example, and check for one or the other. However, it'd be a bit nicer (imo) to just have foo that was either a list or not.

Answer

If you intend to do it this way then just add a check for reverse method, if it has reverse method then its a list else considered single value

{% if foo.reverse %}
    {% for item in foo %}
        {{ item }}<br>
    {% endfor %}
{% else %}
    {{ item}}<br>
{% endif %}