Sometimes, we want to iterate through a list of dictionaries in Jinja template with Python Flask.
In this article, we’ll look at how to iterate through a list of dictionaries in Jinja template with Python Flask.
How to iterate through a list of dictionaries in Jinja template with Python Flask?
To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop.
For instance, we write
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
to create the parent_list
list of dicts.
Then we write
{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}
in our Jinja2 template to render the parent_list
items in a for loop.
And in the for loop, we add another for loop to render the key
and value
from dict_item
which has the dict being looped through in parent_list
.
Conclusion
To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop.