Andishe
Andishe

Reputation: 115

Strting for loop tag inside if else tag raise error

In jinja template there is a for loop in my script, with a start tag {% for each in list_one %} and end tag {% endfor %}.

I want to set 2 conditions for choosing the starting tag of for loop to work. Something like this:

{% if name %}
    {% for each in list_one %}
{% else %}
    {% for each in list_two %}
        {{ each }}
{% endif %}
    {% endfor %}

The error I face with is:

jinja2.exceptions.TemplateSyntaxError:Encountered unknown tag 'endif'. You probably made a nesting mistake. Jinja is expecting this tag, but currently looking for 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.

Upvotes: 0

Views: 382

Answers (2)

Dean Fenster
Dean Fenster

Reputation: 2395

You have to close the for loop before the if clause. In order to decide which list to iterate upon, you can do this instead:

{% if name %}
    {% set desired_list = list_one %}
{% else %}
    {% set desired_list = list_two %}
{% endif %}
{% for each in desired_list %}
    {{ each }}
{% endfor %}

Upvotes: 4

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

You are trying to use for loop both in if and else blocks. But you missed to close for loop before closing your if and else blocks.

The correct code is like:

{% if name %}
    {% for each in list_one %}
    {% endfor %}
{% else %}
    {% for each in list_two %}
        {{ each }}
    {% endfor %}
{% endif %}

Upvotes: 0

Related Questions