twig Basic template syntax Whitespace handling


Example

To remove whitespace (spaces, tabs, newlines…) between HTML tags use spaceless tag:

{% spaceless %}

    <div>
        <span>foo bar </span>
    </div>
{% endspaceless %}
{# produces output <div><strong>foo bar </strong></div> #}

If you need to remove whitespace on a per tag level, use whitespace control modifier i.e. hyphen (-). Using it, you can trim leading and or trailing whitespace:

{% set value = 'foo bar' %}

<span>  {{- value }}  </span> 
{# produces '<span>foo bar  </span>' #}

<span>  {{ value -}}  </span> 
{# produces '<span>  foo bar</span>' #}

<span>  {{- value -}}  </span> 
{# produces '<span>foo bar</span>' #}

<span {%- if true  %} class="foo"{% endif %}>
{# produces '<span class="foo">' #}

<span {%- if false %} class="foo"{% endif %}>
{# produces '<span>' #}