[Django]-How can I tell if a value is a string or a list in Django templates?

11👍

There’s no builtin way to do so. A (somewhat dirty IMHO) workaround would be to implement a custom "is_string" filter, but the best solution would be to preprocess the values in the view to make it an uniform list of tuples (or list).

for the filter solution:

@register.filter
def is_string(val):
    return isinstance(val, basestring)

and then in your templates:

<ul> 
{% for whatever in something %}
  <li>
    {% if whatever|is_string %} 
      {{ whatever }}
    {% else %}
    <ul>
      {{ whatever|unordered_list }}
    </ul>
    {% endif %}
  </li>
{% endfor %}
</ul>

cf the excellent Django doc for more on custom filters and templatetags:

https://docs.djangoproject.com/en/stable/howto/custom-template-tags/

6👍

You can create an isinstance filter in the view or a helper module:

from django.template.defaultfilters import register

@register.filter(name="isinstance")
def isinstance_filter(val, instance_type):
    return isinstance(val, eval(instance_type))

Then in the template you could do:

{% load isinstance %}
{% if some_value|isinstance:"list" %}
  // iterate over list
{% else %}
  // use string
{% endif %}
👤mVChr

Leave a comment