尽管Jinja2文档可能是这样,但它们对于设置变量作用域并不清楚。唯一提到的范围是内部块的范围修饰符,但我想它不能应用到一切...疯狂。
解决方案对于每个循环,都有一个循环对象,它们有一个索引属性。 org / docs / dev / templates /#forrel =nofollow> jinja.pocoo/docs/dev/templates/#for
要访问父循环索引,可以这样做: jinja.pocoo/docs/dev/tricks/#accessing-the-parent-loop
你可以使用enumerate在Jinja中和Python一样工作 https: //docs.python/2/library/functions.html#enumerate
{% 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.
解决方案For each loop, there is a loop object generated which have an index attribute.
jinja.pocoo/docs/dev/templates/#for
To access parent loop index, you can do like this: jinja.pocoo/docs/dev/tricks/#accessing-the-parent-loop
Or you could use enumerate which work the same in Jinja as in Python docs.python/2/library/functions.html#enumerate
更多推荐
Jinja2嵌套循环计数器
发布评论