Managing white space with Jinja3

python

This provides a list without blanks lines between each element, but with no trailing commas:

{% for field in fields +%}
[{{field.name}}] {{field.sqlservertype}} {{field.sqlservernull}}
{% endfor %}

Adding {% if not loop.last %},{% endif %} adds a trailing comma to all but the last element but puts everything on line:

{% for field in fields %}
[{{field.name}}] {{field.sqlservertype}} {{field.sqlservernull}}{% if not loop.last %},{% endif %}
{% endfor %}

Wierd, huh?

The code that works:

Adding a plus sign in the for clause {% for field in fields +%} disables Jinja3’s “trim_blocks” and renders the list without blank lines where each line but the last has a trailing comma:

{% for field in fields +%}
[{{field.name}}] {{field.sqlservertype}} {{field.sqlservernull}}{% if not loop.last %},{% endif %}
{% endfor %}

Read about “trim_blocks” here: https://jinja.palletsprojects.com/en/3.0.x/templates/#whitespace-control