Flask Template Loops
A template loop repeats a block once per item. The {% for %} line starts the loop.
Make the app
This line imports Flask and render_template_string together. The route below renders a list.
from flask import Flask, render_template_string
app = Flask(__name__)Loop over names
The view passes a list of three names. The loop makes one list item per name.
@app.route("/list")
def names():
items = ["Ana", "Bo", "Cy"]
return render_template_string("<ul>{% for name in items %}<li>{{ name }}</li>{% endfor %}</ul>", items=items)Ask for the list
The test client asks for /list and prints the page with all three names.
client = app.test_client()
print(client.get("/list").data.decode())Example
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/list")
def names():
items = ["Ana", "Bo", "Cy"]
return render_template_string("<ul>{% for name in items %}<li>{{ name }}</li>{% endfor %}</ul>", items=items)
client = app.test_client()
print(client.get("/list").data.decode())Key points
- {% for item in items %} repeats the block for each item.
- The loop ends with {% endfor %}.
- Each pass shows the current item.
- Loops build lists without repeating the HTML.
In this example, the view passes a list of three names to the template. The {% for %} loop makes one list item per name. The test client asks for /list and prints the page with all three names.
Note
The loop variable lives only inside the loop.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How many list items does {% for name in items %} make for three names?