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 %}