Jinja2 nested loop counter

别说谁变了你拦得住时间么 提交于 2020-01-01 02:10:09

问题


{% set cnt = 0 %}
{% for room in rooms %}
  {% for bed in room %}
    {% set cnt = cnt + 1 %}
  {% endfor %}
{{ cnt }}
{% endfor %}

Say we have that nested loop, printed cnt will ALWAYS be 0, because that's what it was defined when we entered the 1st for loop. When we increment the counter in the inner loop, it seems to only be a local variable for the inner loop -- so it will increment while inside the loop, but then that local cnt is gone. HOW can we modify the global cnt???

As great as the Jinja2 doc may be, they are unclear about set variable scopes. The only thing mentioning scope was the "scoped" modifier for inner blocks, but I guess it can't be applied to everything ... crazy.


回答1:


Scoping rules prevent you from accessing a variable declared outside a loop from inside the loop

To quote Peter Hollingsworth from his previous answer,

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

{% set cnt = [0] %}
{% for room in rooms %}
  {% for bed in room %}
    {% if cnt.append(cnt.pop() + 1) %}{% endif %} 
  {% endfor %}
{{ cnt[0] }}
{% endfor %}
total times through = {{ cnt[0] }}



回答2:


For each loop, there is a loop object generated which have an index attribute.

http://jinja.pocoo.org/docs/dev/templates/#for

To access parent loop index, you can do like this: http://jinja.pocoo.org/docs/dev/tricks/#accessing-the-parent-loop

Or you could use enumerate which work the same in Jinja as in Python https://docs.python.org/2/library/functions.html#enumerate




回答3:


A very hacky way I recall using in the past:

{% set cnt = 0 %}
{% for room in rooms %}
    {% for bed in room %}
        {% if cnt += 1 %}
    {% endfor %}
{{ cnt }}
{% endfor %}

Not tested.



来源:https://stackoverflow.com/questions/18755046/jinja2-nested-loop-counter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!