📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Flask Web Framework Templates with Jinja2

Templates with Jinja2

5 min read Quiz at the end
Extend base layouts in Jinja2 with blocks, output variables safely, loop data, and apply filters.

Jinja2 Templates

# templates/base.html
<!DOCTYPE html>
<html>
<body>
    {% block content %}{% endblock %}
    {% block scripts %}{% endblock %}
</body>
</html>

# templates/posts/index.html
{% extends "base.html" %}

{% block content %}
<h1>Posts</h1>
{% for post in posts %}
    <h2>{{ post.title | e }}</h2>       {# escaped #}
    <p>{{ post.body | truncate(100) }}</p>
    {% if post.is_draft %}
        <span>Draft</span>
    {% endif %}
{% else %}
    <p>No posts found.</p>
{% endfor %}
{% endblock %}

# In Python
from flask import render_template

@app.route("/posts")
def posts():
    all_posts = Post.query.all()
    return render_template("posts/index.html", posts=all_posts)