Reputation: 20967
My docker .env
file is created from a jinja2 template. I'm using {# ... #}
for comments.
It has this:
FOO={{BAR}} {# blah blah blah #}
SOMETHING=2
I expect it to render:
FOO=1 SOMETHING=2
But it actually renders:
FOO=1 SOMETHING=2
Upvotes: 0
Views: 2645
Reputation: 1821
As @mdaniel pointed out, there are a few ways to adjust Jinja2's whitespace behavior, but a new option has appeared in 3.0.x's documentation that I believe is easiest way to solve the problem:
... you can manually disable the trim_blocks behavior by putting a plus sign (+) at the end of a block:
<div> {% if something +%} yay {% endif %} </div>
Therefore, your specific problem should be easily solved by the insertion of a single plus symbol:
FOO={{BAR}} {# blah blah blah +#}
SOMETHING=2
And if you want to remove the whitespace which would appear between the variable and the comment, explicitly remove it with a minus symbol:
FOO={{BAR}} {#- blah blah blah +#}
SOMETHING=2
trim_blocks
parameterSince this question tags Ansible, I should point out that you can also modify the behavior by setting the trim_blocks
parameter of the ansible.builtin.template
module. This has been part of Ansible since version 2.4. The default is yes
, but you can set it to no
to achieve the desired result.
Hopefully this will help other people who find this question seeking a similar solution.
Upvotes: 4
Reputation: 33221
Jinja2 strips trailing newlines after blocks, as described in the fine manual
You can influence that behavior in at least 3 ways:
#}\n
and thus jinja2 will eat the \n
)#} \n
, although that will make git and some editors mad, since it is considered trailing whitespacetemplate:
context, you can turn off trim_blocks: no
; in certain contexts, you can do that inside the template itself, too, via a #jinja2:trim_blocks:False
header in the template, as described by that template:
documentation pageUpvotes: 2