Whitespace in templates

Hi,

it’s really a minor issue, but it’s at least annoying me in a way that I will ask for advice :slight_smile:

I am creating a config based on this Jinja template:

    listen-on port 53 {
        {% for ip in ips -%}
        {{ ip }};
        {% endfor -%}
    };

ips is a list of IPs, like this:

ips:
  - 10.0.0.53
  - 10.0.2.53
  - 10.0.4.53

Now the result is as follows:

    listen-on port 53 {
        10.0.0.53;
        10.0.2.53;
        10.0.4.53;
        };

Based on the template I would expect the closing curly brace }; to be positioned under the “l” of the “listen-on” statement, but clearly some whitespace has been added in front of it.

I have tried various options as described in Template Designer Documentation — Jinja Documentation (3.1.x) but I can’t get it to work the way I want it to output the config file.

What am I doing wrong ?

The four spaces before the endfor statement are being emitted into the output. I never indent Jinja2 control statements, for this exact reason.

3 Likes

Hi,
As suggested not indent the jinja tag,like this

listen-on port 53 {
{% for ip in ips %}
    {{ ip }};
{% endfor %}
};

Anyway have you tried with this?

listen-on port 53 {
    {%- for ip in ips +%}
    {{ ip }};
    {%- endfor +%}
};

Should be work as same of non-indented jinja.

2 Likes

Right, that indeed did the trick. I wasn’t aware of this issue when indenting the control statements.

I removed it and now the output is as expected.

Thanks a lot !

Thanks, both of these produce the same output.

Regarding the second solution, did you get that from experience, or can you recommend a website (next to the Jinja homepage itself) where this is explained in more detail ?

Something from experience.
Reading the documentation is not clear that we can combine thme, but it’s possible.

1 Like

Try this->

listen-on port 53 {
{% for ip in ips %}
    {{ ip }};
{% endfor -%}
};

The -% was correct… but the problem is that the actual endfor being pushed over to the right, caused the whole thing to space over for that final };

You can try this out with something like: Ansible Template Tester

1 Like

Thanks for the Template Tester link, I will certainly add that to my toolset !

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.