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:

<employee>
    <name>{{ name }}</name>
    {% if age_value %}
    <age>{{ age }}</age>
    {% endif %}
    <title>{{ title }}</title>
</employee>

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

<employee>
    <name>John Doe</name>
    <age>25</age>
    <title>Software Engineer</title>
</employee>

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

<employee>
    <name>John Doe</name>

    <title>Software Engineer</title>
</employee>

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:

<employee>
    <name>{{ name }}</name>
    {%- if age_value %}
    <age>{{ age }}</age>
    {%- endif %}
    <title>{{ title }}</title>
</employee>

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

<employee>
    <name>John Doe</name>
    <title>Software Engineer</title>
</employee>
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

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