17

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.

2 Answers 2

36

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 %}
0

I would recommend looking at Accessing global attributes from inside a macro in Jinja2 and if you are using Flask you could look at template context processors. For what its worth, what I do (in Flask) is create instance variables that are part of the app instance; I don't see why you cannot do the same with the Jinja2 environment. In other words, add your dictionary to Jinja2's environment, and verify what (if anything) is needed to make it available in the template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.