Rendering clean & tidy HTML with TWIG templates

14,913

Solution 1

This page of the documentation should help you control spaces within tags http://twig.sensiolabs.org/doc/templates.html#whitespace-control

Solution 2

I wanted correct output indentation too, so I made an extension for that. I made it available in a gist: https://gist.github.com/urraka/ccd1812570ca4b278b9f

See the usage file from the gist for a bit of an explanation.

Basically, this template:

{# Given variable = "line1\nline2\nline3" #}

<body>
    {% if true %}
        <stuff>{% if true %}only blocks that take the whole line have effect{% endif %}</stuff>
        {{ variable }}
    {% endif %}
</body>

would end up like this:

<body>
    <stuff>only blocks that take the whole line have effect</stuff>
    line1
    line2
    line3
</body>
Share:
14,913
Max
Author by

Max

Analytics consultant available for hire. More info: https://maxcorbeau.com

Updated on June 14, 2022

Comments

  • Max
    Max almost 2 years

    I've been playing with Twig (version 1.9.1) as a PHP templating engine, and I'm not totally satisfied with the rendered HTML as extra unwanted line-breaks and spaces are added which make the result quite untidy. To make my templates more flexible, I am using macros which can call each other in a nested fashion, which in itself works fine, but seems to make things worse. For instance, a <a> element is rendered as follows:

                 <a href="http://google.com" alt="some alternative text">                    some text with <strong>some html</strong>
    
    
    
    </a>
    

    I know that part of the reason is the way my twig templates are formatted, as if I remove empty lines and indenting from them, the rendered HTML looks a bit more tidy, but not completely: the below output shows a rendered <a> with still 2 line breaks between the start and end of the element, despite the corresponding template not containing any empty lines or spaces!:

    <a href="http://google.com" alt="some alternative text">some text with <strong>some html</strong>
    
    
    </a>
    

    Even though it helps, removing formatting from my twig templates (i.e. empty lines and indenting) isn't really an option as it makes my template very hard to read and maintain.

    Apart from removing formatting from templates. what are the ways to render a cleaner/tidier HTML with Twig?