twig tutorial - Whitespace handling in Twig - twig php - twig template



Whitespace handling

  • 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>' #}

Related Searches to twig tutorial - Whitespace handling in Twig