Jinja2嵌套循环计数器

编程入门 行业动态 更新时间:2024-10-24 12:27:39
本文介绍了Jinja2嵌套循环计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

{%set cnt = 0%} {%for room in rooms%} {%for bed in room%} {设置cnt = cnt + 1%} {%endfor%} {{cnt}} {%endfor%} 尽管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嵌套循环计数器

本文发布于:2023-11-29 23:08:19,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   计数器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!