Search code examples
jinja2

Check if an array is not empty in Jinja2


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?


Solution

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