Loops with Jinja
Jinja provides control structures that allow us to loop through lists while rendering the template.
For loops start with {% for my_item in my_collection %}
and end with {% endfor %}
. Here my_item
is a loop variable that will be taking values as we go over the elements. And my_collection
is the name of the variable holding reference to the iterated collection.
@app.route("/articles")
def articles():
articles = [
{"title": "article 1", "url": "https://example.com/article-1"},
{"title": "article 2", "url": "https://example.com/article-2"},
{"title": "article 3", "url": "https://example.com/article-3"}
]
return render_template("article_list.html", articles = articles)ython
{% for article in articles %}
<p>
<a href="{{article.url}}">{{ article.title|capitalize }}</a>
</p>
{% endfor%}
Last updated
Was this helpful?