Blank lines in Jinja2 Templates

When working with the Jinja2 templating engine on Python I’ve been bugged by blank lines that got inserted into the resultant XML when an optional node was excluded from the output. ¬†Though Jinja2 sports some support for controlling whitespace I had never happened upon an answer on how to ensure that no needless blank lines ended up in the XML output.

Given the following template:

{{ name }}
{% if age_value %}
{{ age }}
{% endif %}
{{ title }}

If age is supplied to the template then the output looks great:

John Doe
25
Software Engineer

The problem occurs when this optional value is not available. We end up with a blank line where the age node would be:

John Doe

Software Engineer

Jinja2’s templating markup provides for the use of the ‘-‘ character before or after code blocks to strip out whitespace. So modifying the template ever so slightly to look this like:

{{ name }}
{%- if age_value %}
{{ age }}
{%- endif %}
{{ title }}

results in clean output that excludes the blank line when the optional node is left out:

John Doe
Software Engineer
This entry was posted in Programming, Python and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *