Search code examples
pythonhtmlflaskjinja2

Add 1 to variable in Flask HTMl


I'm using a for loop to change a variable's value. +1 each time the for loop goes This is my HTML code:

{% set count = 1 %}
        {% for i in form %}
            <label>
                <input type="radio" name="test" value="{{ i['Name'] }}">
                <div class="grid-item">{{ i["Name"] }}</div>
                {{ count }}
            </label>
            {% set count = count + 1 %}
        {% endfor %}

The problem is that count always stays 1. If I put the {% set count = count + 1 %} before the {{ count }} then count is always equal to 2.

I tested it in python and there it works,

Does anybody know what could be the problem?


Solution

  • Simply use the loop.index counter variable.

    {% for i in form %}
        <label>
            <input type="radio" name="test" value="{{ i.Name }}">
            <div class="grid-item">{{ i.Name }}</div>
            {{ loop.index }}
        </label>
    {% endfor %}