Jinja - Loop over a list

by
Jeremy Canfield |
Updated: September 10 2023
| Jinja articles
Here is a basic example of how to loop over a list of values in Jinja.
{% set fruits=['apple','banana','grape','orange'] %}
{% for fruit in fruits %}
{{ fruit }}
{% endfor %}
Or, you can print a specific index item from the list. In this example, index item 0 (apple) will be printed.
{% set fruits=['apple','banana','grape','orange'] %}
{% for fruit in fruits %}
{{ fruit[0] }}
{% endfor %}
Sometimes, you'll pass the results of a SQL query into a Jinja template. For example, let's say "results" contains SQL that contains a "firstname" row. Here is how you can sort the results.
{% for row in result | sort(attribute='firstname') %}
{{ row['firstname'] }}
{% endfor %}
Did you find this article helpful?
If so, consider buying me a coffee over at