Jinja docx template, avoiding new line in nested for

Viewed 18752

I was wondering if there is a way to avoid newline characters inside a for in a docx template with jinja. The code is as follows:

{% for customer in customers %}
{% for account in customer.accounts %}
{{ account.number }}
{% endfor %}{% endfor %}. 

But the result is account numbers separated by row:

234090

29292

29292

I'm testing on LibreOffice.

Could someone help me?

5 Answers

Inspired by das-g answer, I had a similar issue, after a lot of trial and error I gave up and decided to always remove the newlines but add newline break by hand like he did, but only if not last index of loop, so my macro ended up like this:

{% macro service_envs() %}
{% if app_envs is defined %}
    environment:
{% for env in app_envs %}
      - {{ env }}{% if not loop.last %}{{ '\n' }}{% endif %}
{%- endfor %}
{% endif %}
{% endmacro %}

The result is:

    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    ports:
      - 5432:5432

The important part is removing spaces in the {%- endfor %} but adding it in the if statement. So in my case the spaces were preserved, but I had no newline for last item of list. So my next line would be just after my environment list. Now I don't need to add {{- }} every time i call the macro. Tested with ansible version 2.5.0

Thanks for @das-g's detailed comments. He explained how the space comes but didn't clarify how Jinja eats the white space. I would like to add some comments here for me and for other people having the same issue.

{%- for customer in customers %}: remove white space before for-loop block

{% for customer in customers -%}: remove white space before each for-loop item

{%- endfor %}: remove white space after each for-loop item

{% endfor -%}: remove white space after for-loop block

In a simple word,

{% for %} has a line break after this tag, that is {% for %}¶

{% for -%} first remove the line-break after the tag then expand the loop

same idea for the endfor tag

If a new line is not required then we can put the statements in single line as <% for … %><% if … %><% endif %><% endfor %>.

With this Jinj2, parsing will not introduce a new line.

Related