35

What's the difference between this:

{%block body %}

and that

{%block body -%}
nonlux
  • 774
  • 2
  • 6
  • 20
  • possible duplicate of [What does the hyphen mean for a block in Twig like in {% block body -%}?](http://stackoverflow.com/questions/17298902/what-does-the-hyphen-mean-for-a-block-in-twig-like-in-block-body) – Dave Newton Jul 20 '15 at 20:40
  • 5
    Yes but I asked May 19 '13 at 11:56 and Michaël Perrin asked Jun 25 '13 at 13:38. And on this page we have great answer from SirDerpington – nonlux Jul 21 '15 at 00:35

1 Answers1

50

Just read something about it in the documentation, not sure if this will also apply on {% block ... %} tags. Twig whitespace control

{% set value = 'no spaces' %}
    {#- No leading/trailing whitespace -#}
    {%- if true -%}
        {{- value -}}
    {%- endif -%}
{# output 'no spaces' #}

There's also another example given which trims the whitespace in front of the variable but doesnt't do it at the end - so the effect is only on one side.

{% set value = 'no spaces' %}
    <li>    {{- value }}    </li>
{# outputs '<li>no spaces    </li>' #}

The above sample shows the default whitespace control modifier, and how you can use it to remove whitespace around tags. Trimming space will consume all whitespace for that side of the tag. It is possible to use whitespace trimming on one side of a tag

So I think the difference in your given exmaples is that in the first block body there will be a whitespace after the block started. In your second example body - there's none after the block started. Just read the documentation entry to see how it works.

EDIT

A simple example to demonstrate the example in the docu:

{% set value = 'NO space in source code after/before "value"' %}
<li>    {{- value -}}    </li>
...

outputs in Firebug in the HTML markup: no whitespaces afer value

Whereas this

{% set value = 'space in source code after "value"' %}
<li>    {{- value }}    </li>
...

ouputs:

whitespace between "value" and closing </li>

Notice the space between "value" and the closing </li> in the second example. So the minus - erases/trims a whitespace either before, after or on both sides of e.g. a variable.

SirDerpington
  • 11,260
  • 4
  • 49
  • 55
  • 1
    Would be interesting to understand if the "whitespace control modifier" is needed just regarding markup or if it is needed also between *TWIG* instructions divided by spaces (like ```{% if true %} (space|newline in template) {% set something = {} %}```), **and** if the modifier would be needed on both sides (```.. true -%}``` / ```{%- set ..```) or just one is enough. – Kamafeather Oct 14 '15 at 12:14
  • 1
    Ok, I just tried it. Actually it matters. But just one modifier (on ```true %}``` or on ```{% set```) is enough. Otherwise seems that all the spacings are considered (either between pure TWIG instructions without HTML markup). – Kamafeather Oct 14 '15 at 12:23