Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array is not empty in Jinja2

Tags:

jinja2

People also ask

How do I find the length of a list in Jinja?

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count ) is documented to: Return the number of items of a sequence or mapping. @wvxvw this does work: {% set item_count = items | length %} as long as items is a list, dict, etc.

What is Jinja2 syntax?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


I think your best bet is a combination of defined() check along with looking at the length of the array via length() function:

{% if texts is defined and texts|length > 0 %}
    ...
{% endif %}

To test for presence ("defined-ness"?), use is defined.

To test that a present list is not empty, use the list itself as the condition.

While it doesn't seem to apply to your example, this form of the emptiness check is useful if you need something other than a loop.

An artificial example might be

{% if (texts is defined) and texts %}
    The first text is {{ texts[0] }}
{% else %}
    Error!
{% endif %}

Take a look at the documentation of Jinja2 defined(): http://jinja.pocoo.org/docs/templates/#defined

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}

Is it clear enough? In your case it could look like this:

{% if texts is defined %}
    {% for text in texts %} 
        <div>{{ error }}</div>
        <div class="post">
            <div class="post-title">{{ text.subject }}</div>
            <pre class="post-content">{{ text.content }}</pre>
        </div>
    {% endfor %}
{% else %}
    Error!
{% endif %}

As mentioned in the documentation, you could also write:

{% for text in texts %}
    <div class="post">
        <div class="post-title">{{text.subject}}</div>
        <pre class="post-content">{{text.content}}</pre>
    </div>
{% else %}
    <div>{{ error }}</div>
{% endfor %}

It handles both the case where texts is undefined, and the case where texts is empty.