DEV Community

Cover image for HTML whitespace control
Florian Stolzenhain
Florian Stolzenhain

Posted on

HTML whitespace control

Original post on my blog, happy to include feedback!
Cover: NASA, via New Old Stock

Assuming you're wrangling with whitespace-critical code like

<a href="#">
    <!-- will display an additional space character -->
    my link text
</a>
Enter fullscreen mode Exit fullscreen mode

you could either remove whitespace in your template

<a href="#">my link text</a>
Enter fullscreen mode Exit fullscreen mode

or use your templater's whitespace control:

Handlebars

<a href="#">
    {{!-- will remove whitespace on each side of the tilde --}}
    {{~ text ~}}
</a>
Enter fullscreen mode Exit fullscreen mode

see also: Expressions | Handlebars / Whitespace Control

Twig

<a href="#">
    {# remove whitespace on each side of the tilde #}
    {{- text -}}
</a>
Enter fullscreen mode Exit fullscreen mode
<a href="#">
    {# remove whitespace on each side of the tilde – not newlines #}
    {{~ text ~}}
</a>
Enter fullscreen mode Exit fullscreen mode
{# suppress whitespace in this region #}
{% spaceless %}
<a href="#">
    {{ text }}
</a>
{% endspaceless %}
Enter fullscreen mode Exit fullscreen mode

see also: Twig – spaceless

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more