42  Jinja2: Syntax

42.1 Basic Syntax

42.1.1 Variables

{{ variable }}
{{ user.name }}
{{ user['name'] }}
{{ user.get('name', 'default') }}

42.1.2 Comments

{# This is a comment and won't be rendered in the output #}

42.1.3 Statements

{% statement %}

42.2 Control Structures

42.2.1 If Statements

{% if condition %}
    Content if condition is true
{% elif another_condition %}
    Content if another_condition is true
{% else %}
    Content if all conditions are false
{% endif %}

42.2.2 For Loops

{% for item in items %}
    {{ item }}
{% endfor %}

{% for key, value in dictionary.items() %}
    {{ key }}: {{ value }}
{% endfor %}

{% for item in items %}
    {{ loop.index }}      {# 1-based index #}
    {{ loop.index0 }}     {# 0-based index #}
    {{ loop.first }}      {# True if first iteration #}
    {{ loop.last }}       {# True if last iteration #}
    {{ loop.length }}     {# Total number of items #}
{% else %}
    No items found
{% endfor %}

42.3 Template Inheritance

42.3.1 Base Template

{# base.html #}
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <header>{% block header %}Default Header{% endblock %}</header>
    <main>{% block content %}{% endblock %}</main>
    <footer>{% block footer %}Default Footer{% endblock %}</footer>
</body>
</html>

42.3.2 Child Template

{# child.html #}
{% extends "base.html" %}

{% block title %}Page Title{% endblock %}

{% block content %}
    <h1>Page Content</h1>
    <p>This replaces the content block from the parent template</p>
    
    {# Include parent block content #}
    {{ super() }}
{% endblock %}

42.4 Includes and Imports

42.4.1 Include

{% include 'header.html' %}
{% include 'sidebar.html' ignore missing %}

42.4.2 Import

{% import 'macros.html' as macros %}
{{ macros.input('username') }}

{% from 'macros.html' import input %}
{{ input('username') }}

42.5 Macros (Reusable Template Functions)

42.5.1 Define Macro

{% macro input(name, value='', type='text') %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
{% endmacro %}

42.5.2 Use Macro

{{ input('username') }}
{{ input('password', type='password') }}

42.6 Filters

42.6.1 String Filters

{{ name|capitalize }}         {# First letter capitalized #}
{{ name|upper }}              {# All uppercase #}
{{ name|lower }}              {# All lowercase #}
{{ name|title }}              {# Title Case #}
{{ name|trim }}               {# Remove whitespace from both ends #}
{{ name|replace('old', 'new') }} {# Replace text #}
{{ name|truncate(50) }}       {# Truncate to 50 chars #}

42.6.2 List Filters

{{ list|join(', ') }}         {# Join list items #}
{{ list|first }}              {# First item #}
{{ list|last }}               {# Last item #}
{{ list|length }}             {# Number of items #}
{{ list|sort }}               {# Sort items #}
{{ list|reverse }}            {# Reverse order #}

42.6.3 Custom Filters (Python Side)

def date_filter(value, format='%Y-%m-%d'):
    return value.strftime(format)

env.filters['date'] = date_filter
{{ post.date|date }}
{{ post.date|date('%B %d, %Y') }}

42.7 Tests

{% if variable is defined %}
{% if number is divisibleby(3) %}
{% if value is none %}
{% if string is upper %}

Common tests:

  • defined, undefined
  • none, sameas(other)
  • odd, even, divisibleby(number)
  • string, number, iterable, mapping

42.8 Whitespace Control

{%- if condition -%}    {# Remove whitespace on both sides #}
    Content
{%- endif -%}

{{- variable -}}         {# Remove whitespace on both sides #}

42.9 Set & Block Variables

{% set name = 'John' %}
{% set users = [1, 2, 3] %}
{% set users = users + [4, 5] %}

{% set navigation %}
    <li><a href="/">Home</a></li>
    <li><a href="/about">About</a></li>
{% endset %}

42.10 Raw Content (No Processing)

{% raw %}
    This {{ will not }} be processed by Jinja2
{% endraw %}

42.11 Extensions & Advanced Features

42.11.1 Expression Statement

{% do users.append('john') %}  {# Do something without output #}

42.11.2 With Statement

{% with foo = 42 %}
    {{ foo }}             {# foo is 42 here #}
{% endwith %}

42.11.3 Assignments

{% set users = ['John', 'Jane'] %}

42.11.4 Line Statements

# for item in items
    {{ item }}
# endfor

42.11.5 Template Context (Python Side)

template.render(
    title="My Page",
    users=["John", "Jane"],
    is_admin=True
)

42.12 Error Handling

{{ missing_variable|default('default value') }}

This cheat sheet covers the most commonly used Jinja2 syntax elements and features. Keep it handy as you build your templates!