Whitespace Control

In the default configuration:

  • a single trailing newline is stripped if present

  • other whitespace (spaces, tabs, newlines etc.) is returned unchanged

If an application configures Jinja to trim_blocks, the first newline after atemplate tag is removed automatically (like in PHP). The _lstrip_blocks_option can also be set to strip tabs and spaces from the beginning of aline to the start of a block. (Nothing will be stripped if there areother characters before the start of the block.)

With both trim_blocks and lstrip_blocks enabled, you can put block tagson their own lines, and the entire block line will be removed whenrendered, preserving the whitespace of the contents. For example,without the trim_blocks and lstrip_blocks options, this template:

  1. <div>
  2. {% if True %}
  3. yay
  4. {% endif %}
  5. </div>

gets rendered with blank lines inside the div:

  1. <div>
  2. yay
  3. </div>

But with both trim_blocks and lstrip_blocks enabled, the template blocklines are removed and other whitespace is preserved:

  1. <div>
  2. yay
  3. </div>

You can manually disable the lstrip_blocks behavior by putting aplus sign (+) at the start of a block:

  1. <div>
  2. {%+ if something %}yay{% endif %}
  3. </div>

You can also strip whitespace in templates by hand. If you add a minussign (-) to the start or end of a block (e.g. a For tag), acomment, or a variable expression, the whitespaces before or afterthat block will be removed:

  1. {% for item in seq -%}
  2. {{ item }}
  3. {%- endfor %}

This will yield all elements without whitespace between them. If seq wasa list of numbers from 1 to 9, the output would be 123456789.

If Line Statements are enabled, they strip leading whitespaceautomatically up to the beginning of the line.

By default, Jinja2 also removes trailing newlines. To keep singletrailing newlines, configure Jinja to keep_trailing_newline.

Note

You must not add whitespace between the tag and the minus sign.

valid:

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

invalid:

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