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

前端 未结 7 2089
旧时难觅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条回答
  •  -上瘾入骨i
    2020-11-27 12:40

    As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.

    You can defeat this behavior by using an object rather than a scalar for 'count':

    {% set count = [1] %}
    

    You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):

    {% if count.append(count.pop() + 1) %}{% endif %} {# increment count by 1 #}
    

提交回复
热议问题