Check if an array is not empty in Jinja2

daniel__ picture daniel__ · May 8, 2012 · Viewed 68.3k times · Source

I need to check if the variable texts is defined or not in index.html.

If the variable is defined and not empty then I should render the loop. Otherwise, I want to show the error message {{error}}.

Basically this in PHP

if (isset($texts) && !empty($texts)) {
    for () { ... }
}
else {
    print $error;
}

index.html

{% 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 %}

How do I say this in jinja2?

Answer

phs picture phs · May 5, 2015

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 %}