[Twig] How to control whitespaces

When coding, you may want to remove spaces between html tags, line breaks, etc.
I will explain how to control whitespace in Twig.

How to use the whitespace control modifier “-“: Remove whitespace

Whitespace can be removed by using the modifier - in the description of Twig tags and variables.

Usage example

{% set foo = 'test' %}

// sample1 remove all whitespace (including newlines)
    {{- foo }}    </li>
// result
<li>test    </li>

// sample2 removes all whitespace (excluding newlines)
    {{~ foo }}    </li>
// result

As you can see from the sample, the space (line feed) on the side with - is deleted.

Use Filter to control whitespace

You can also use the spaceless filter to remove whitespace.
In this case, remove the whitespace for the filtered value.

{{ "<div>
    "|spaceless }}

// result

Use as above.
By using the apply tag, it can be applied to all the parts enclosed by the tag.

{% apply spaceless %}
        foo bar
{% endapply %}

// result
<div>foo bar</div>

apply is a tag that applies to the part surrounding the filter.
It is convenient to remember because it can be used with other filters.

* In Twig 2.x, there was a tag {% spaceless %}.
It works in the same way as apply above.