Skip to content

Jinja

Basic Syntax

Variable Interpolation

{{ variable }}

Expressions

{{ 1 + 2 }}
{{ "Hello" ~ "World" }}
{{ variable | length }}

Template Inheritance

Base Template

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
    {% block content %}{% endblock %}
</body>
</html>

Child Template

{% extends "base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
<h1>Welcome to the Home Page</h1>
<p>This is the content of the home page.</p>
{% endblock %}

Control Structures

If Statement

{% if user %}
    Hello, {{ user }}!
{% else %}
    Hello, Guest!
{% endif %}

For Loop

<ul>
    {% for item in items %}
    <li>{{ item }}</li>
    {% endfor %}
</ul>

Macros

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

<p>{{ input('username') }}</p>

Filters

Applying Filters

{{ "hello world" | capitalize }}
{{ [1, 2, 3] | sum }}

Custom Filters

def reverse_filter(s):
    return s[::-1]

env.filters['reverse'] = reverse_filter
{{ "hello" | reverse }}

Include and Import

Include Template

{% include "header.html" %}
<p>Main content goes here...</p>
{% include "footer.html" %}

Import Macros

{% import "macros.html" as macros %}
<p>{{ macros.input('username') }}</p>

Template Comments

{# This is a comment #}

Escaping

Autoescaping

{% autoescape true %}
    {{ user_input }}
{% endautoescape %}

Manual Escaping

{{ user_input | escape }}

Setting Variables

{% set username = "John Doe" %}
<p>Hello, {{ username }}!</p>

Loop Controls

Loop Variables

{% for item in items %}
    {{ loop.index }} - {{ item }}
{% endfor %}

Break and Continue

{% for item in items %}
    {% if item == "skip" %}
        {% continue %}
    {% endif %}
    {% if item == "stop" %}
        {% break %}
    {% endif %}
    {{ item }}
{% endfor %}

Whitespace Control

{% raw %}
{% for item in items %}
    {{ item }}
{% endfor %}
{% endraw %}
{{- variable -}}
{%+ tag -%}

Extending Jinja2

Custom Functions

def custom_function():
    return "Hello from custom function"

env.globals['custom_function'] = custom_function
<p>{{ custom_function() }}</p>

Custom Tests

def is_even(n):
    return n % 2 == 0

env.tests['even'] = is_even
{% if variable is even %}
    <p>{{ variable }} is even</p>
{% endif %}