Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja: Check if variable is iterable

Is there a way in Jinja to check if a variable is iterable? I'm working with Django and depening on whether I use objects.filter or objects.get the response is send to the jinja template is could be iterable or not.

I tried the following:

{% extends 'header.html' %}

{% block content %}
{% if response is iterable %}
    {% for i in response %}
        <p>i</p>
    {% endfor %}
{% else %}
     {{ response }}
{% endif %}
{% endblock %}

However, Django throws: Unused 'is' at end of if expression.

like image 334
theCed7 Avatar asked Jan 23 '26 17:01

theCed7


1 Answers

The above answer no longer works for me, however the below does:

{% if response is iterable %}

One caveat with this though is that it would deem a string iterable (which it is) and would then loop over every letter in the string, a more appropriate check might be:

{% if response is iterable and response is not string %}

like image 102
Peter Featherstone Avatar answered Jan 26 '26 10:01

Peter Featherstone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!