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.attrMeaning
loop.index1-based iteration count
loop.index00-based
loop.first / loop.lastboolean
loop.lengthtotal 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 | safe on content you fully trust. Otherwise = XSS risk.

πŸ”— Next

Flask Static Files & Blueprints Β· Flask Forms & WTForms