How to loop over a list or dictionary in a Flask template using Jinja2 synta
Published on Aug. 22, 2023, 12:16 p.m.
To loop over a list or dictionary in a Flask template using Jinja2 syntax, you can use the for
loop syntax. Here are some examples:
Loop over a list:
{% for item in my_list %}
{{ item }}
{% endfor %}
my_list
is a Python list passed in from the view function to the template. This will output each item in the list.
Loop over a dictionary:
{% for key, value in my_dict.items() %}
{{ key }}: {{ value }}
{% endfor %}
my_dict
is a Python dictionary passed in from the view function to the template. This will output each key-value pair in the dictionary.
Note that the syntax of Jinja2 is similar to that of Django’s template language, with some differences. You can find more information on Jinja2 syntax in the official documentation.