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

**URL:** <https://forum.ansible.com/t/keep-items-of-for-loop-on-the-same-line-but-adding-a-new-line-when-the-loop-is-done-jinja-template/32381>\
**Category:** Ansible Project\
**Created:** [March 4, 2020, 1:17pm UTC](https://forum.ansible.com/t/keep-items-of-for-loop-on-the-same-line-but-adding-a-new-line-when-the-loop-is-done-jinja-template/32381 "2020-03-04T13:17:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![K\_de\_Jong](https://avatars.discourse-cdn.com/v4/letter/k/51bf81/32.png) [@K\_de\_Jong](https://forum.ansible.com/u/K_de_Jong)\
**Post date:** [March 4, 2020, 1:17pm UTC](https://forum.ansible.com/t/keep-items-of-for-loop-on-the-same-line-but-adding-a-new-line-when-the-loop-is-done-jinja-template/32381/1 "2020-03-04T13:17:07Z")

</div>

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.

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

```

Output

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

```

Prefered output:

```auto
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.

---

<div class="post-metadata">

**Author:** ![Dick\_Visser](https://avatars.discourse-cdn.com/v4/letter/d/d9b06d/32.png) [@Dick\_Visser](https://forum.ansible.com/u/Dick_Visser)\
**Post date:** [March 4, 2020, 1:44pm UTC](https://forum.ansible.com/t/keep-items-of-for-loop-on-the-same-line-but-adding-a-new-line-when-the-loop-is-done-jinja-template/32381/2 "2020-03-04T13:44:47Z")

</div>

That's exactly what I do in those cases 🙂
