Flask Templates (Jinja2)
π Setup
myproject/
βββ app.py
βββ templates/
βββ home.html
from flask import render_template
@app.route("/")
def home():
return render_template("home.html", title="Welcome", user="Amit")π€ Variables and expressions
{{ variable }}
{{ user.name }} {# attribute access #}
{{ user['name'] }} {# bracket, same result #}
{{ items[0] }} {# indexing #}
{{ price * 1.1 }} {# arithmetic #}
{{ "Yes" if logged_in else "No" }} {# inline conditional #}Missing attribute β renders blank, doesn't crash. Watch for silent typos.
π Control structures
{% if user.is_admin %}
admin
{% elif user.is_member %}
member
{% else %}
guest
{% endif %}
{% for item in items %}
{{ loop.index }}: {{ item.name }}
{% else %}
no items {# runs if items is empty #}
{% endfor %}| loop.attr | Meaning |
|---|---|
loop.index | 1-based iteration count |
loop.index0 | 0-based |
loop.first / loop.last | boolean |
loop.length | total items |
π§± Template inheritance
<!-- base.html -->
<title>{% block title %}My Site{% endblock %}</title>
<main>{% block content %}{% endblock %}</main><!-- home.html -->
{% extends "base.html" %}
{% block title %}Home{% endblock %}
{% block content %}<h1>Welcome</h1>{% endblock %}
{% extends %}must be the first line in the child template.
π§© Includes
{% include "partials/navbar.html" %}include = paste a fragment in place. extends = override blocks in a shared layout.
π Linking
<a href="{{ url_for('about') }}">About</a>
<a href="{{ url_for('static', filename='style.css') }}">CSS</a>π§Ή Filters
{{ name | upper }}
{{ name | lower }}
{{ description | truncate(50) }}
{{ items | length }}
{{ price | round(2) }}
{{ user.bio | default("No bio") }}
{{ name | trim | upper }} {# chainable #}π‘οΈ Auto-escaping
{{ user_comment }} {# escaped by default, safe #}
{{ trusted_html | safe }} {# disables escaping #}Only use
| safeon content you fully trust. Otherwise = XSS risk.