Search code examples
twig

What does the hyphen (dash) mean for a Twig block like in {% block body -%}?


When generating a CRUD in a Symfony2 application with Doctrine commands, generated Twig template content is defined within a Twig block this way:

{% block body -%}

{% endblock %}

What does the hyphen (dash) in -%} mean? It works fine without the hyphen and I could not find anything similar in the Twig documentation.


Solution

  • A hyphen (or dash) at the end of a Twig block means to trim trailing whitespace, at the beginning, leading whitespace. Both means... both.

    See the Whitespace Control section of the docs; their example:

    {% set value = 'no spaces' %}
    {#- No leading/trailing whitespace -#}
    {%- if true -%}
        {{- value -}}
    {%- endif -%}
    {# output 'no spaces' #}
    
    <li>
        {{ value }}    </li>
    {# outputs '<li>\n    no spaces    </li>' #}
    
    <li>
        {{- value }}    </li>
    {# outputs '<li>no spaces    </li>' #}
    
    <li>
        {{~ value }}    </li>
    {# outputs '<li>\no spaces    </li>' #}