Check if an array is not empty in Jinja2

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

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

Tags:

Jinja2