Trim whitespace (trailing newline) at the end of included Twig template

1.2k Views Asked by At

I’m trying to include a Twig template inside another, but there is undesirable whitespace which is caused by the trailing newline in the included template.

My use case is that the include takes place mid-sentence, just before a comma, and I don’t want any whitespace before the comma.

Base template:

Né le {{ include("date.html.twig", {date: date}) }}, décédé le…

Included template:

<time datetime="...">
  {{- date.format() -}}
</time>

Desired result :

Né le 6 mai 1977, décédé le…

Actual result :

Né le 6 mai 1977 , décédé le…

I can confirm the trailing newline is the cause of the issue, but removing it is not a viable solution to me since most tools are configured to add it if it’s missing.

Is there any way to trim this trailing newline?

1

There are 1 best solutions below

0
On BEST ANSWER

I found the solution while writing the question:

Ending the included template with a Twig tag seems to be enough. So I ended up wrapping the content in a spaceless filter:

{% apply spaceless %}
<time datetime="...">
  {{- date.format() -}}
</time>
{% endapply %}

Technically using {% if true %} … {%- endif %} also works, but is much less understandable.

- modifiers are still needed inside <time> because spaceless only removes whitespace between HTML tags, not inside.