如何在Jinja2中中断for循环? [英] How can I break a for loop in jinja2?
问题描述
如何在jinja2中打破for循环?
How can I break out of a for loop in jinja2?
我的代码是这样的:
<a href="#">
{% for page in pages if page.tags['foo'] == bar %}
{{page.title}}
{% break %}
{% endfor %}
</a>
我有多个具有此条件的页面,一旦满足条件,我想结束循环.
I have more than one page that has this condition and I want to end the loop, once the condition has been met.
推荐答案
您不能使用break
,而是使用过滤器.从Jinja2 关于{% for %}
的文档:
You can't use break
, you'd filter instead. From the Jinja2 documentation on {% for %}
:
与Python不同,它不可能在循环中中断或继续.但是,您可以在迭代过程中过滤序列,从而可以跳过项目.下面的示例跳过所有隐藏的用户:
Unlike in Python it’s not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skips all the users which are hidden:
{% for user in users if not user.hidden %}
<li>{{ user.username|e }}</li>
{% endfor %}
但是,对于您来说,您似乎只需要 first 元素;只需过滤并选择第一个:
In your case, however, you appear to only need the first element; just filter and pick the first:
{{ (pages|selectattr('tags.foo', 'eq', bar)|first).title }}
这使用 selectattr()
过滤器过滤列表,结果传递给 first
过滤器.
This filters the list using the selectattr()
filter, the result of which is passed to the first
filter.
selectattr()
过滤器会生成一个迭代器,因此在此处使用first
只会对输入进行迭代,直到第一个匹配元素为止,而不会进行进一步的迭代.
The selectattr()
filter produces an iterator, so using first
here will only iterate over the input up to the first matching element, and no further.
这篇关于如何在Jinja2中中断for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!