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

Top comments (0)