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:
{% if age_value %}
{{ age }}
{% endif %}
{{ title }}
If age is supplied to the template then the output looks great:
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:
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:
{%- if age_value %}
{{ age }}
{%- endif %}
{{ title }}
results in clean output that excludes the blank line when the optional node is left out:
Software Engineer
Thank you!