Jinja

Whitespace and Escaping

Navigation

Contents

This section of the documentation explains how to remove unused whitespace from the templates and embed raw Jinja syntax.

Escaping

Sometimes you might want to add Jinja syntax elements into the template without executing them. In that case you have quite a few possibilities.

For small parts this might be a good way:

{{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}

When you have multiple elements you can use the raw block:

{% raw %}
    Filtering blocks works like this in Jinja:
    {% filter escape %}
        <html>
          <code>goes here</code>
        </html>
    {% endfilter %}
{% endraw %}

Whitespace

If the Jinja environment was created with trim_blocks set to true the first newline after a template tag is removed automatically (php like processing).

Starting with Jinja 1.1 you can also handle some whitespace rules in the template. If you put an minus sign (-) to the start or end of an block (for example a for tag), a comment or variable element you can remove the whitespaces after or before that block:

{% for item in seq -%}
    {{ item }}
{%- endfor %}

This will yield all elements without whitespace between them because they are automatically removed. This of course works for other tags too:

{% for user in userlist -%}
    {{ user|e -}}
    {% if not loop.last %},{% endif %}
{%- endfor %}

Note that you must not use a whitespace between the tag and the minus sign:

valid:
    {%- if foo -%}...{% endif %}

invalid:

    {% - if foo - %}...{% endif %}