shayms8
shayms8

Reputation: 771

Apply if statement inside for loop in Python Jinja Templates

I got this simple HTML template:

{% block html_page %}
    {% set counter = 1 %}    
    {% for field in fields %}
        COUNTER: {{ counter }} <br>
        {% set counter = counter+1 %}

    {% endfor %}

{% endblock %}

Where fieldscontains 4 items.

The output is:

COUNTER: 1 
COUNTER: 1 
COUNTER: 1 
COUNTER: 1

While the output i want should be with the counter increasing:

COUNTER: 1 
COUNTER: 2 
COUNTER: 3 
COUNTER: 4

The counter assignment is being done INSIDE the for loop, so I don't get why does it keep returning to 1.

Any suggestions?

Upvotes: 0

Views: 879

Answers (1)

Maciej M
Maciej M

Reputation: 786

This doesn't work due to scoping rules in Jinja.

After Jinja 2.10, to solve the scope problem, you can do something like this:

{% set count = namespace(a=0) %}
{% for field in fields %}
  {{ count.a }}
  {% set count.a = count.a + 1 %}
{% endfor %}

Or you could use loop.index:

{% for field in fields %}
  {{ loop.index }}
{% endfor %}

Upvotes: 2

Related Questions