Running a for-loop over a Jinja2 dictionary
At the time of this posting, iterating over dictionaries inside a Jinja template is poorly documented, especially if you need access to the jinja dictionary keys and it's something I end up doing alot.
Of course running a for-loop over a jinja dictionary is as basic an activity as you're likely to do, for whatever reason it's buried in the Jinja2 documentation. I see thousands of people trying to find out how to do it hitting this page every day.
So here's how you do it, nice and simple...
#1: The Simple Way
Loop over each item in a sequence. For example, to display a list of users provided in a variable called users:
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
#2: Using iteritems()
If you need to retain both the key and value when doing a for-loop over a jinja dictionary, use iteritems() like this...
<ul>
{% for key, value in _dict.iteritems() %}
<dt>{{ key }}</dt>
<dd>{{ value }}</dd>
{% endfor %}
</dl>
Note, however, that Python dicts are not ordered; so you might want pass a sorted list of tuples instead.
Doing these things in Jinja is easy after you know. See the full API: http://jinja.pocoo.org/docs/api/
To: @mattccrampton
0
Other Posts
When exporting photos from a service like Flickr, perhaps after they've given notice that they're going to delete our photos if you don't subscribe to......
All Truthy and Falsy Javascript Values In Nodejs, every value has an associated boolean, true or false, value. For example, a null value has an......
Google Forcing Nest Cameras Visual Indicator Light To Be On Received the following email from Google today... Full email text... Recently, we shared our commitment......
Posting to Twitter with Python - Part Two: Posting Photos NOTE: This is part two of my posting to Twitter with Python tutorial. If you......
Doubleclick to open a file in VIM from OSX I use VIM for just about everything from note taking to coding to keeping track of......
Sign Into Gmail Without Signing Into Google Chrome Unfortunately, Google has made changes to Chrome since this blog post was posted which removed the options......