如何在 jinja 模板中的 for 循环上增加变量?
我想做类似的事情:
变量 p 来自 test.py,它是一个列表 ['a','b','c','d']
{% for i in p %}
{{variable++}}
{{variable}}
结果输出是:
1 2 3 4
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}}
result output is:
1 2 3 4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果有人想在循环内添加一个值,那么你可以使用它,它的工作 100%
输出 = 5
if anyone want to add a value inside loop then you can use this its working 100%
output = 5
来寻找 Django 的方法并找到了这篇文章。也许其他人需要 django 解决方案来到这里。
在这里阅读更多内容:
https://docs.djangoproject.com/en/1.11/ref/templates /内置/
Came searching for Django's way of doing this and found this post. Maybe someone else need the django solution who come here.
Read more here:
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/
我也为这种行为而挣扎。我想根据计数器更改 jinja 中的 div 类。我很惊讶 pythonic 方式不起作用。以下代码在每次迭代时重置我的计数器,因此我只有红色类。
我像这样使用了loop.index并且它有效:
I was struggle with this behavior too. I wanted to change div class in jinja based on counter. I was surprised that pythonic way did not work. Following code was reseting my counter on each iteration, so I had only red class.
I used loop.index like this and it works:
只是为了让更多人了解这个问题。
Jinja2 变量的行为与传统脚本语言不同,您无法在 for 循环中修改变量。因此,要绕过此行为,您可以使用字典,因为您可以更改字典的值。
在上面的代码中,字典的值被修改。
Just to shed more light into this problem.
Jinja2 variables behaves differently from that of conventional scripting languages, you can't modify the variable in a for loop.Hence to bypass this behaviour you can use a dictionary, since you can change the value of the dictionary.
In the above code the value of the dictionary is being modified.
您可以使用
loop.index
:查看模板设计器文档。
在较新的版本中,由于范围规则,以下内容将不起作用:
You could use
loop.index
:Check the template designer documentation.
In more recent versions, due to scoping rules, the following would not work:
2.10之后,要解决范围问题,可以这样做:
After 2.10, to solve the scope problem, you can do something like this:
正如 Jeroen 所说,存在范围问题:如果您在循环外部设置“count”,则无法在循环内部修改它。
您可以通过使用对象而不是标量来表示“计数”来克服此行为:
您现在可以在 for 循环甚至 %include% 内操作计数。以下是我增加计数的方法(是的,这很笨拙,但是哦):
或者...
(来自@eyettea和@PYB的评论)
As Jeroen says there are scoping issues: if you set 'count' outside the loop, you can't modify it inside the loop.
You can defeat this behavior by using an object rather than a scalar for 'count':
You can now manipulate count inside a forloop or even an %include%. Here's how I increment count (yes, it's kludgy but oh well):
Or...
(From comments by @eyettea and @PYB)
这是我的解决方案:
将所有计数器放入字典中:
定义一个宏以轻松增加它们:
现在,只要您愿意增加“counter1”计数器,只需执行以下操作:
Here's my solution:
Put all the counters in a dictionary:
Define a macro to increment them easily:
Now, whenever you want to increment the 'counter1' counter, just do: