如何在 jinja2 中中断 for 循环? [英] How can I break a for loop in jinja2?

查看:78
本文介绍了如何在 jinja2 中中断 for 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何跳出 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆