Keep indent level for included Twig substring

I work with the Twig template engine and want to include a link under the template in the following example:

<header> <div id="menu"> {% include 'menu.twig' %} </div> </header> 

The input file contains the following code:

 <ul> <li>item 1</li> <li>item 2</li> </ul> 

Twig now generates the following HTML:

 <header> <div id="menu"> <ul> <li>item 1</li> <li>item 2</li> </ul> </div> </header> 

As you can see, the indentation level is only correct for the first line of the included file, which leads to the fact that the code is higher, which is rather untidy and bad to maintain.

How can I get the correct output from Twig with the right indentation like this?

 <header> <div id="menu"> <ul> <li>item 1</li> <li>item 2</li> </ul> </div> </header> 
+5
source share
2 answers

I don't think there is a way to support indentation when templates are included. The only solution I can imagine is to pass the level of indentation in the variable and use the loop in the included template to prefix this number of spaces in each line. Obviously, this β€œdecision” would be crazy and a nightmare to maintain.

Regarding this comment: "[...] which leads to the above code, which is pretty untidy and bad to maintain." I would like to say the following:

  • It doesn't matter if the HTML is "untidy". Browsers will not complain, and users do not see this.
  • It is true that it is bad to maintain. Fortunately, you support a beautifully aligned Twig template, rather than generated HTML code.

All of the above will be different if the Twig template generates a format in which "perfect alignment" is mandatory. But in the case of HTML, please do not waste time aligning tags.

+1
source

If you just want to keep the exact indent of the included subpattern, you can do this:

 <header> <div id="menu"> {% include 'menu.twig' %} </div> </header> 

i.e. put all the include directives at the beginning of the line. The result will be:

 <header> <div id="menu"> <ul> <li>item 1</li> <li>item 2</li> </ul> </div> </header> 

But somehow I feel that this is not enough. Another solution is to add padding to the sublayer, i.e.

  <ul> <li>item 1</li> <li>item 2</li> </ul> 

but, of course, it only works if the sub-tier is always included in a certain level of indentation.

I suggest you choose a completely different route and format the response after that it generates, for example. with kernel.response event listener.

+1
source

All Articles