October CMS resources and help articles

Simple and to the point. Optimized by the community.

Properly indent page content rendered by the {% page %} twig tag

3
by mjauvin, last modified on April 17th, 2020

If you would like the rendered html page content to be properly indented, use the following in your plugin's registration file:

public function boot()
{   
    \Event::listen('cms.page.render', function ($controller, $content) {
        $layout = $controller->getLayoutObject();
        $tabs = $layout->tabs ?: 4;
        $tabSize = $layout->tabSize ?: 4;

        $result = []; 
        $indentation = $tabs * $tabSize;
        foreach (explode(PHP_EOL, $content) as $line) {
            $result[] = str_repeat(' ', $indentation) . $line;
        }   
        return implode("\n", $result);
    }); 
}

You can override the number of tabs and tabSize within yout layout's onInit() function like this:

description = "Basic layout example"
==
public function onInit()
{
    $this['tabs'] = 2;
    $this['tabSize'] = 3;
}
==
...
<body style="height:100%; overflow-x:hidden">
    <div class="container-fluid px-0">
        {%~ page ~%}
    </div>
</body>
...

Note: the "~" removes whitespaces but leaves new lines

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?