For Loop in HTML Template in Python Flask

Flask – For loop in HTML template

In a flask application, we can write For Loop statement in HTML template.

Flask is bundled with Jinja2 language. This enables us to include variables, If statements, or Loop statements in the HTML template.

In this tutorial, we will learn how to write a For Loop in HTML template, in a Python flask application.

The following is a simple code snippet to write For Loop statement in HTML template.

{% for item in some_collection: %}
<li>{{ item }}</li>
{% endfor %}

where for, in, endfor are keywords, and also colon symbol : after collection, is part of syntax. You may replace some_collection with your required collection. Inside the For loop, you have access to the item in the respective iteration.

Also, please observe that the code is enclosed in braces and percentile symbols.

You can write as many number of HTML lines as required inside For Loop.


In this example, flask application, we will write a For Loop to populate list items in HTML template index.html.

Consider a flask application with the following project structure.

Python flask project structure

from flask import Flask, render_template, request

app = Flask(__name__)

def home_page():
    fruits = ['apple', 'banana', 'cherry']
    return render_template("index.html", fruits=fruits)

if __name__ == "__main__":"", port=8080, debug=True)

We read the value for URL parameter 'username' using the expression request.args['username'], pass it to the HTML template, and use this value in the condition of if-statement.


<!DOCTYPE html>
  <h1>Hello User!</h1>
    {% for item in fruits: %}
    <li>{{ item }}</li>
    {% endfor %}
  <p>Welcome to sample flask application by <a href=""></a>.</p>

Run Application

Open terminal or command prompt at the root of the flask application, and run the Python file

Run Flask Application

The flask application is up and running at URL

Now, open a browser of your choice and hit the URL

Python Flask - For Loop in HTML template

The For Loop has been executed for each item in the collection fruits.

Project ZIP


In this Python Flask Tutorial, we learned how to write a For-statement in HTML template, with the help of an example flask application.

Related Tutorials

Code copied to clipboard successfully 👍