This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Jinja & Jinja2 Template Cheatsheet

A quick reference guide for Jinja template syntax in Python/Flask: variables, filters, control structures, loops, template inheritance, and macros.

· Published

Jinja is a fast, expressive, and extensible templating engine for Python, widely used in Flask and Ansible.

Syntax Delimiters

{% ... %}  # Control statements (loops, conditionals, block definitions)
{{ ... }}  # Expressions evaluated and printed to template output
{# ... #}  # Template comments (stripped from final output)

Variables & Filters

<h1>Hello {{ user.name | capitalize }}</h1>
<p>{{ article.body | truncate(150) | safe }}</p>
<p>Items count: {{ items | length }}</p>

Common filters: capitalize, lower, upper, title, trim, striptags, join, default, safe.

Control Structures

Conditionals

{% if user.is_authenticated %}
  <p>Welcome back, {{ user.name }}!</p>
{% elif user.is_invited %}
  <p>Please complete your registration.</p>
{% else %}
  <a href="/login">Sign in</a>
{% endif %}

Loops

<ul>
{% for item in items %}
  <li class="{{ 'odd' if loop.odd else 'even' }}">
    {{ loop.index }}: {{ item.title }}
  </li>
{% else %}
  <li>No items available.</li>
{% endfor %}
</ul>

Loop helpers: loop.index (1-based), loop.index0 (0-based), loop.first, loop.last, loop.length.

Template Inheritance

Base layout (base.html):

<!DOCTYPE html>
<html>
<head><title>{% block title %}My Site{% endblock %}</title></head>
<body>
  <main>{% block content %}{% endblock %}</main>
</body>
</html>

Child template:

{% extends "base.html" %}
{% block title %}Dashboard - My Site{% endblock %}
{% block content %}
  <h1>Welcome to your Dashboard</h1>
{% endblock %}

References

Related topics