Keep items of for loop on the same line, but adding a new line when the loop is done (Jinja template)

The template code below is from my Postfix setup in Ansible. What I want to do is to put all domain names on a single line with a comma+space as separator. To do this, I make use of the “{%-” syntax. However, at the end of the loop, the line after the for loop is also removed. Which puts the mydomain line on the same as masquerade_domains. This is not what I want. I only want to keep the items of the for loop on the same line.

masquerade_domains = $mydomain{% for item in query('dict', network) if item.value.domain is defined %}
, {{ item.value.domain }}
{%- endfor %}
mydomain = {{ domain.example.name }}

Output

masquerade_domains = $mydomain, home.lan, vpn.home.lanmydomain = example.com

Prefered output:

masquerade_domains = $mydomain, home.lan, vpn.home.lan
mydomain = example.com

As you can see, the masquerade_domains and mydomain lines are on one line, rather than on seperate lines.

I tried:

  • Putting #jinja2: lstrip_blocks: True, trim_blocks: False at the top of the file
  • Experimenting with “{%-” rather than just “{%”
  • Experimenting with {%- if not loop.last %} and then I tried to strip only the lines before the last line, however, I kept repeating the same output.

What works: When I put a new line after the endfor then mydomain is put on the correct line after masquerade_domains line. However, this seems like an ugly solution. There must be a way to handle this in the Jinja templating.

That's exactly what I do in those cases :slight_smile: