How to iterate through a list of dictionaries in Jinja template?
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
.
{% for i in yourlist %}
{% for k,v in i.items() %}
{# do what you want here #}
{% endfor %}
{% endfor %}
As a sidenote to @Navaneethan 's answer, Jinja2
is able to do "regular" item selections for the list and the dictionary, given we know the key of the dictionary, or the locations of items in the list.
Data:
parent_dict = [{'A':'val1','B':'val2', 'content': [["1.1", "2.2"]]},{'A':'val3','B':'val4', 'content': [["3.3", "4.4"]]}]
in Jinja2 iteration:
{% for dict_item in parent_dict %}
This example has {{dict_item['A']}} and {{dict_item['B']}}:
with the content --
{% for item in dict_item['content'] %}{{item[0]}} and {{item[1]}}{% endfor %}.
{% endfor %}
The rendered output:
This example has val1 and val2:
with the content --
1.1 and 2.2.
This example has val3 and val4:
with the content --
3.3 and 4.4.