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) <li> {{- foo }} </li> // result <li>test </li> // sample2 removes all whitespace (excluding newlines) <li> {{~ foo }} </li> // result <li> test</li>
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> foo </div> "|spaceless }} // result <div>foo</div>
Use as above.
By using the apply
tag, it can be applied to all the parts enclosed by the tag.
{% apply spaceless %} <div> foo bar </div> {% 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.