Controlling Whitespace in Jinja (and Why It Matters)
Jinja2 is a templating engine used in Autologyx to dynamically generate content using data, logic, and expressions.
When working with Jinja, it is important to understand how whitespace is handled, as it can affect the validity and formatting of your output.
By default, Jinja preserves whitespace, including spaces and line breaks. While this can improve template readability, it can also lead to unexpected or invalid output.
In cases where exact values are required—such as Booleans, JSON, or API payloads—extra whitespace can cause errors or incorrect behaviour.
Example: Whitespace Causing Invalid Output
Consider a Boolean local variable. The output must be strictly true or false, with no additional characters.
{% if 1 == 1 %}
true
{% else %}
false
{% endif %}Although this is readable, it renders with leading/trailing spaces and line breaks, resulting in an invalid Boolean value.
Solution: Use Whitespace Control
Jinja provides whitespace control using a hyphen (-), known as a whitespace control modifier. This removes whitespace before or after a block.
{%- if 1 == 1 -%}
true
{%- else -%}
false
{%- endif -%}Even though the template includes spacing for readability, Jinja strips all surrounding whitespace.
The final output is exactly:
true
(or false), with no extra characters.
Document Automation Example (Including For Loops)
When generating documents, whitespace can create visible layout issues.
Without whitespace control
{% for item in items %}Item: {{ item }}
{% endfor %}This renders a line break before and after each item, resulting in two line breaks between consecutive items. In document generation, these blank lines may accumulate and cause unintended spacing or even additional blank pages.
With whitespace control
{%- for item in items -%}Item: {{ item }}
{%- endfor -%}This removes the extra line breaks, producing clean, consistent output without unintended gaps.
Other Common Use Cases
Whitespace control is important anywhere exact output is required, including:
- Boolean variables — must be exactly
trueorfalse - JSON generation — extra whitespace can break formatting or validation
- API request bodies — unexpected characters can cause request failures
- Document automation — when using Jinja to render documents, whitespace around control structures (such as for loops) can introduce unintended blank lines or page breaks. This may result in extra blank pages in generated documents.
Key Takeaway
Jinja does not automatically trim whitespace. Use {%- and -%} to ensure your output is clean, predictable, and free from unintended whitespace when formatting matters.