How to iterate through a list of dictionaries in Jinja template?

user3089927 picture user3089927 · Aug 19, 2014 · Viewed 182.5k times · Source

I tried:

list1 = [{"username": "abhi", "pass": 2087}]
return render_template("file_output.html", list1=list1)

In the template:

<table border=2>
  <tr>
    <td>
      Key
    </td>
    <td>
      Value
    </td>
  </tr>
  {% for dictionary in list1 %}
    {% for key in dictionary %}
      <tr>
        <td>
          <h3>{{ key }}</h3>
        </td>
        <td>
          <h3>{{ dictionary[key] }}</h3>
        </td>
      </tr>
    {% endfor %}
  {% endfor %}
</table>

The above code is splitting each element into multiple characters:

[

{

"

u

s

e

r

...

I tested the above nested loop in a simple Python script and it works fine but not in Jinja template.

Answer

Nava picture Nava · Aug 19, 2014

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
   {% for key, value in dict_item.items() %}
      <h1>Key: {{key}}</h1>
      <h2>Value: {{value}}</h2>
   {% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py. If the dict is unicode object, you have to encode into utf-8.