I have the following template code in our codebase that renders Jinja2 and/or Nunjucks depending on the situation:
<a href="#">
{%- include 'logo.j2' -%}{%- include 'icon.j2' -%}
</a>
where logo.j2 and icon.j2 both contain a single <svg>
Jinja2 is rendering this how I would expect, where I get ...</svg><svg>... in my output. However, Nunjucks is insisting on returning ...</svg>\n<svg>... no matter what I try. How can I have these tags touch in the output?
Ah, I see the issue. From the jinja2 docs:
By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.
We don't copy this behavior in nunjucks, and I'm actually rather surprised that Jinja2 does this by default. From this discussion it sounds like it was originally a bug, or at least unintentional, but folks started relying on the trailing-newline-stripping so they made it configurable with a setting to keep backwards compatibility.
I'm not sure it makes sense to follow jinja2's lead on this, though I could be convinced otherwise. The most straightforward way to get rid of the \n is to remove the trailing newline in the included files.
Maybe I'm overstating it by saying that it was originally unintentional. If the only thing being rendered is html, and given that some editors always add a trailing newline to a file, I can understand why some might find the trailing-newline-stripping preferable. And since {% include %} isn't part of an open/close tag, I could see why {%- include -%} might be expected to do to the included file what it would have done for {%- if -%}...{%- endif -%}
So, would it be possible or favorable to at least add a global flag/option to Nunjucks to get it to behave the same as Jinja2's default behavior?
Most helpful comment
So, would it be possible or favorable to at least add a global flag/option to Nunjucks to get it to behave the same as Jinja2's default behavior?