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.
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.
Break and Continue can be added to Jinja2 using the loop controls extension. Jinja Loop Control Just add the extension to the jinja environment.
jinja_env = Environment(extensions=['jinja2.ext.loopcontrols'])
as per sb32134 comment
But if you for some reason need a loop you can check the loop index inside for-loop block using "loop.first":
{% for dict in list_of_dict %}
{% for key, value in dict.items() if loop.first %}
<th>{{ key }}</th>
{% endfor %}
{% endfor %}