Controlling whitespace in 11ty with Nunjucks

May 11, 2024 • • 🍿 2 min. read in eleventy

TIL today if you are using Nunjucks for your 11ty templating language, then you can strip all whitespace in HTML loop output using a hypen either site of the statement (so at the end of the opening nunjucks tag and the start of the closing tag).

So this:

{% if tags %}
{% for tag in tags %}
<a href="/blog/on/{{ tag | safe }}/" class="tag">{{ tag }}</a>
{% endfor %}
{% endif %}

becomes this:

{% if tags -%}
{% for tag in tags -%}
<a href="/blog/on/{{ tag | safe }}/" class="tag">{{ tag }}</a>
{%- endfor %}
{%- endif %}

and all whitespace is removed. Super useful for CSS styling where whitespace matters. Nice!


Posted in eleventy