FORSMILE
JA
Twig2021/02/08

[Twig] How to Control Whitespace

When coding, you might sometimes want to remove spaces between HTML tags or newlines.

← Back to Blog
Twig syntax guide

When coding, you might sometimes want to remove spaces between HTML tags or newlines.

USING THE WHITESPACE CONTROL MODIFIER '-' TO REMOVE WHITESPACE

You can remove whitespace by using the '-' modifier in Twig tags or variable declarations.

Examples

css
{% 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 examples, whitespace (including newlines) on the side where '-' is applied will be removed.

CONTROLLING WHITESPACE USING FILTERS

You can also remove whitespace by using the `spaceless` filter.

In this case, the filter removes whitespace from the value to which it is applied.

css
{{ "<div>
        foo
    </div>
    "|spaceless }}

// result
<div>foo</div>

By using the `apply` tag, you can apply it to the entire section enclosed by the tags.

css
{% apply spaceless %}
    <div>
        foo bar
    </div>
{% endapply %}

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

The `apply` tag applies a filter to the entire block of code it encloses.

Note: In Twig 2.x, there was a `{% spaceless %}` tag.

RECOMMENDED BOOKS FOR TWIG

I haven't read any books exclusively focused on Twig, but I found one on Amazon Kindle.

📦
Search Amazon US for related books and tools
PHP Twig template engine
Search Amazon US → (affiliate link). As an Amazon Associate, we earn from qualifying purchases.
Related articles