How to increment a variable on a for loop in jinja template?

前端 未结 7 2087
旧时难觅i
旧时难觅i 2020-11-27 12:02

I would like to do something like:

variable p is from test.py which is a list [\'a\',\'b\',\'c\',\'d\']

{% for i in p %}
{{variable++}}
{{variable}}
         


        
7条回答
  •  离开以前
    2020-11-27 12:23

    I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class.

    {% if sloupec3: %}
        {% set counter = 1 %}
        {% for row in sloupec3: %}
            {% if counter == 3 %}
                {% set counter = 1 %}        
            {% endif %} 
    
            {% if  counter == 1: %}
               
    some red div
    {% endif %} {% if counter == 2: %}
    some gray div
    {% endif %} {% set counter = counter + 1 %} {% endfor %} {% endif %}

    I used loop.index like this and it works:

    {% if sloupec3: %}
    
        {% for row in sloupec3: %} 
    
            {% if  loop.index % 2 == 1: %}
               
    some red div
    {% endif %} {% if loop.index % 2 == 0: %}
    some gray div
    {% endif %} {% endfor %} {% endif %}

提交回复
热议问题