Controlling whitespace in Twig

Author: Matt
Monday, July 18 2016

Recently I discovered the finer controls for whitespace within twig, beyond just the 'spaceless' option.

Twig has a {% spaceless %} option, that strips out all whitespace within HTML tags for the content within it:

{% spaceless %}
    <div class="my-awesome-thing">
        <span>Lorem ipsum dolor sit amet</span>
    </div>
{% endspaceless %}

{# the output will be the following: <div class="my-awesome-thing"><span>Lorem ipsum dolor sit amet</span></div> #}

But while customising form rendering in Symfony, I was looking through the default templates used and noticed some syntax I wasn't familiar with:

{{- block('form_widget_simple') -}}

What were those dashes for?

It turns out that you can control whitespace on a per-tag level, not just through the {% spaceless %} option!

Given the following:

{% set value = 'Lorem ipsum dolor sit amet' %}
<span>    {{- value -}}    </span>

{# the output will be the following: <span>Lorem ipsum dolor sit amet</span> #}

You can also control it per-side of the tag too:

{% set value = 'Lorem ipsum dolor sit amet' %}
<span>    {{ value -}}    </span>

{# the output will be the following: <span>    Lorem ipsum dolor sit amet</span> #}

This functionality was added in version 1.1 of Twig.

Whitespace control documentation

Services in Twig Swift Mailer, Symfony and spooling emails for testing purposes