Running a for-loop over a Jinja2 dictionary

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

Pause reading for 5 seconds...
Join My Mailing List!
Note: I will never share your email with anyone else.
Awesome! Thanks so much.
Submitting...
Ok, lets continue.

#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/

Post A Twitter Response To This Blog Post

To: @mattccrampton

0