Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 for loop with conditions

I have a data structure similar to

data = {{'value': 1, 'state': False},
        {'value': 2, 'state': True}}

Where the state and value will change based on outside conditions.

I want to use a Jinja2 for ... else loop with conditions, like

{% for item in data where item.state == True %}
   {{ item.value }}
{% else %}
   no true items
{% endfor %}

I use the data structure in multiple places, and sometimes it all needs to be displayed. I'd like to only keep one copy of the structure, and have the Jinja2 template take care of either displaying the items with state == True or a message that there aren't any items, rather than having to pre-process it in Python before giving it to the template, or splitting the structure into multiple pieces.

This is running on Google App Engine with Python 2.7 and Jinja2 2.6, and the data structure is backed by memcache.

like image 512
Carson Morrow Avatar asked Sep 29 '12 18:09

Carson Morrow


People also ask

How do you make a 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 write if condition in Jinja?

Jinja in-line conditionals are started with a curly brace and a % symbol, like {% if condition %} and closed with {% endif %} . You can optionally include both {% elif %} and {% else %} tags.


1 Answers

Is this what you're looking for:

 {% for item in data if item.status %}
   {{ item.value }}
 {% else %}
   no true items
 {% endfor %}
like image 196
Arsh Singh Avatar answered Sep 30 '22 07:09

Arsh Singh