Home »
Python
For loop in Flask template engine
Python Flask: In this tutorial, we are going to learn about the for loop in the Flask Template Engine in Python with examples.
Submitted by Sapna Deraje Radhakrishna, on October 16, 2019
Flask comes with a Jinja templating language. The template essentially contains variables as well as some programming logic, which when evaluated are rendered into HTML with actual values. The variables and/or logic are placed between tags or delimiters.
Jinja templates are HTML files which by flask conventions are placed in the templates folder in the Flask project.
Having a loop of the list of users or any list as a matter is a very obvious requirement in a web application. It would be very naïve and unmanageable to add a new page for every new item in the list. Here is where the for-loop in the jinja templates are useful.
Consider the following example,
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/jinja")
def jinja_test():
return render_template('include_help.html', my_string="Include Help!", my_list=[0,1,2,3,4,5])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005)
In the above example, when in the browser the user navigates to http://localhost:5005/jinja the rendered web page will sequentially display the list number.
The list could as simple as a list of numbers or users or profiles to make it complex.
The 'include_help.html' is implemented as
<html>
<head>
<title>Include help Template Example</title>
</head>
<body>
<p>{{my_string}}</p>
<p>Your lucky number is ;) : {{my_list[3]}}</p>
<p>Loop through the list:</p>
<ul>
{% for n in my_list %}
<li>{{n}}</li>
{% endfor %}
</ul>
</body>
</html>
On rendering of the template, the my_string and my_list is replaced with the actual values sent from the backend code. The my_list is then iterated using a for loop. The for loop starts with a for and ends with endfor inside the {%%} tag.
On running the above code, the html rendered is,