← Flask tutorial

Flask

Templates with Jinja2

render_template() renders an HTML file from the templates/ folder using Jinja2.

Example: rendering a list of posts

from flask import render_template

@app.route("/posts")
def posts():
    posts = ["First post", "Second post"]
    return render_template("posts.html", posts=posts)

# templates/posts.html:
# <ul>
# {% for post in posts %}
#   <li>{{ post }}</li>
# {% endfor %}
# </ul>
Renders a bulleted list: First post, Second post

Jinja2 uses the same {{ variable }} and {% for %}/{% if %} tag style Django templates use — no coincidence, since Jinja2 was directly inspired by Django's template language. If you've read the Django tutorial's Templates lesson, this syntax should already feel familiar.

Example
from flask import render_template

@app.route("/posts")
def posts():
    posts = ["First post", "Second post"]
    return render_template("posts.html", posts=posts)

# templates/posts.html
# <ul>
# {% for post in posts %}
#   <li>{{ post }}</li>
# {% endfor %}
# </ul>
Output
Renders a bulleted list containing "First post" and "Second post".