how tune twig without whitespaces

1.6k views Asked by At

How remove whitespaces within tag in twig? Project writin on Symfony2. In twig's documentation advised to use {{- value -}}. I not world want use {%- -%}, because i have to add this block at each tag. if use spaceless, then it remove whitespace between HTML tags, but not delete spaces into a tag.

<p>"
             text"</p>
2

There are 2 answers

2
Raphaël Malié On BEST ANSWER

You can use the spaceless tag :

{% spaceless %}
    <div>
        <strong>foo</strong>
    </div>
{% endspaceless %}

{# output will be <div><strong>foo</strong></div> #}

More informations here on the official documentation : http://twig.sensiolabs.org/doc/tags/spaceless.html

2
Jovan Perovic On

As @Raphaël suggested, you could use {% spaceless %}. Here is an idea to solve that with a single usage:

<html>
    <head>
    </head>
    <body>
        {% spaceless %}
            {% block someBlock %}
            {% endblock %}
        {% endspaceless %}
    </body>
</html>

Now, each template that inherits this one will have spacess removed whatever you put in block named someblock.

Hope this helps...

Edit:

You've got me thinking... you are actually after the trim() function, aren't you? If so you could:

{{ someDynamicText|trim }}

This does not apply to static content as you could easily trim those yourself...