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

前端 未结 7 2112
旧时难觅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:20

    Here's my solution:

    Put all the counters in a dictionary:

    {% set counter = {
        'counter1': 0,
        'counter2': 0,
        'etc': 0,
        } %}
    

    Define a macro to increment them easily:

    {% macro increment(dct, key, inc=1)%}
        {% if dct.update({key: dct[key] + inc}) %} {% endif %}
    {% endmacro %}
    

    Now, whenever you want to increment the 'counter1' counter, just do:

    {{ increment(counter, 'counter1') }}
    

提交回复
热议问题