Python 如何在 jinja2 中中断 for 循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22150273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:22:50  来源:igfitidea点击:

How can I break a for loop in jinja2?

pythonfor-loopjinja2

提问by Taxellool

How can I break out of a for loop in jinja2?

如何跳出 jinja2 中的 for 循环?

my code is like this:

我的代码是这样的:

<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.

我有不止一个页面具有此条件,一旦满足条件,我想结束循环。

采纳答案by Martijn Pieters

You can't use break, you'd filter instead. From the Jinja2 documentation on {% for %}:

你不能使用break,你会过滤。从 Jinja2文档中{% for %}

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 %}

与 Python 不同,不可能在循环中中断或继续。但是,您可以在迭代期间过滤序列,从而可以跳过项目。以下示例跳过所有隐藏的用户:

{% for user in users if not user.hidden %}
    <li>{{ user.username|e }}</li>
{% endfor %}

In your case, however, you appear to only need the firstelement; just filter and pick the first:

但是,在您的情况下,您似乎只需要第一个元素;只需过滤并选择第一个:

{{ (pages|selectattr('tags.foo', 'eq', bar)|first).title }}

This filters the list using the selectattr()filter, the result of which is passed to the firstfilter.

这将使用selectattr()过滤器过滤列表,其结果将传递给first过滤器

The selectattr()filter produces an iterator, so using firsthere will only iterate over the input up to the first matching element, and no further.

selectattr()滤波器产生一个迭代,因此,使用first这里将仅遍历输入到第一匹配部件,并且没有进一步的。

回答by Nikolay Bystritskiy

But if you for some reason need a loop you can check the loop index inside for-loop block using "loop.first":

但是,如果您出于某种原因需要循环,您可以使用“loop.first”检查 for-loop 块内的循环索引:

{% for dict in list_of_dict %} 
    {% for key, value in dict.items() if loop.first %}
      <th>{{ key }}</th>
    {% endfor %} 
{% endfor %}

回答by oneklc

Breakand Continuecan be added to Jinja2 using the loop controls extension. Jinja Loop ControlJust add the extension to the jinja environment.

可以使用循环控件扩展将中断继续添加到 Jinja2。 Jinja Loop Control只需将扩展添加到 jinja 环境中。

jinja_env = Environment(extensions=['jinja2.ext.loopcontrols'])

as per sb32134 comment

根据sb32134 评论