如何使用 Jinja2 模板制作一个简单的计数器?
我有两个 for 循环,两者在尊严上都是相似的。我希望在每次内部迭代期间增加一个计数器。
例如,考虑这个模板:
from jinja2 import Template
print Template("""
{% set count = 0 -%}
{% for i in 'a', 'b', 'c' -%}
{% for j in 'x', 'y', 'z' -%}
i={{i}}, j={{j}}, count={{count}}
{% set count = count + 1 -%}
{% endfor -%}
{% endfor -%}
""").render()
这不应该打印 count=0
到 count=8
吗? 不,没有。
i=a, j=x, count=0
i=a, j=y, count=1
i=a, j=z, count=2
i=b, j=x, count=0
i=b, j=y, count=1
i=b, j=z, count=2
i=c, j=x, count=0
i=c, j=y, count=1
i=c, j=z, count=2
有什么作用?
注意:我不能简单地保存外部循环
变量来计算计数器,因为在我的软件中,内部迭代的次数是可变的。
I have two for loops, both alike in dignity. I'd like to have a counter incremented during each inner iteration.
For example, consider this template:
from jinja2 import Template
print Template("""
{% set count = 0 -%}
{% for i in 'a', 'b', 'c' -%}
{% for j in 'x', 'y', 'z' -%}
i={{i}}, j={{j}}, count={{count}}
{% set count = count + 1 -%}
{% endfor -%}
{% endfor -%}
""").render()
Shouldn't this print count=0
through count=8
? Nope, it doesn't.
i=a, j=x, count=0
i=a, j=y, count=1
i=a, j=z, count=2
i=b, j=x, count=0
i=b, j=y, count=1
i=b, j=z, count=2
i=c, j=x, count=0
i=c, j=y, count=1
i=c, j=z, count=2
What gives?
Note: I can't simply save the outer loop
variable to calculate the counter because, in my software, the number of inner iterations is variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于可变的内部组大小,这将起作用:
...打印:
我猜在超过一级范围之外声明的变量不能分配给或其他东西。
With variable inner group sizes, this will work:
...which prints:
I guess variables declared outside up more than one level of scope can't be assigned to or something.
它看起来确实像一个错误,但是将一些计算移到模板之外怎么样?
输出:
It does look like a bug, but how about moving some of that calculation outside the template?
Output:
为了解决这样的用例,我编写了一个小型环境过滤器来计算某个键的出现次数。
这是 myfilters.py 的代码(带有文档测试):
设置您的环境注册我们的自定义过滤器:
在您的模板上,像这样使用它:
...打印:
To solve use cases like this one, I wrote a small environment filter that counts occurences of a key.
Here's de code (with doc test) of myfilters.py:
Setup your environment registering our custom filter:
And on your template, use it like this:
...which prints:
有内置的全局函数 cycler() 提供与循环无关的值循环。使用相同的想法,您可以定义自己的
counter()
函数,如下所示:这是实现该函数的类:
下面是如何使用它:
它将呈现:
There is builtin global function cycler() providing loop-independent value cycling. Using the same idea you can define your own
counter()
function like this:Here is the class that implements the function:
And here is how to use it:
It is gonna render:
从 Jinja 版本 2.10 开始,现在有一个使用命名空间的更简单的解决方案:
结果:
参见 模板设计器文档 ->|类 jinja-globals.namespace(...)
Since Jinja version 2.10 there is now a simpler solution using namespace:
Result:
see Template Designer Documentation ->| class jinja-globals.namespace(...)
无需添加计数器。您可以像这样访问外循环的索引:
No need to add a counter. You can access the outer loop's index like this: