Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
Taxellool Avatar asked Mar 03 '14 15:03

Taxellool


People also ask

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

How do you escape Jinja template?

To escape jinja2 syntax in a jinja2 template with Python Flask, we can put render the template code without interpretation by putting the code in the {% raw %} block.

How do you iterate through a list in Jinja?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.


2 Answers

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.

like image 173
Martijn Pieters Avatar answered Sep 17 '22 14:09

Martijn Pieters


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

like image 38
oneklc Avatar answered Sep 18 '22 14:09

oneklc