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.

Example

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

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(host="127.0.0.1", 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.

index.html

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

Run Application

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

Run Flask Application

The flask application is up and running at URL http://127.0.0.1:8080/.

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/.

Python Flask - For Loop in HTML template

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

Project ZIP

Summary

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 👍