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.
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.
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.
Is this what you're looking for:
{% for item in data if item.status %}
{{ item.value }}
{% else %}
no true items
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With