Search code examples
pythongoogle-app-enginejinja2

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 would like 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.


Solution

  • You can combine for-loops with if-conditionals to conditionally handle (or filter) loop items like this:

    {% for item in data if item.state %}
        {{ item.value }}
    {% else %}
        no true items
    {% endfor %}