← 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".
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account