Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

python - How can I break a for loop in jinja2?

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't use break, you'd filter instead. From the Jinja2 documentation on {% 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 %}

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...