October CMS resources and help articles

Simple and to the point. Optimized by the community.

Render twig content from a string

0
by mjauvin, last modified on December 5th, 2019

If you want to render twig content contained in a string (a textarea field for example), you can do so with a little magic as shown below.

First, add this to your Plugin's register method:

    Event::listen('cms.page.init', function ($controller) {
            \App::singleton('cms.twig.environment', function ($app) use ($controller) {
                    return $controller->getTwig();
            });
    });

Then, add this twig filter to your Plugin.php:

    public function registerMarkupTags()
    {   
        return [
            'filters' => [
                'twig' => function ($content, $vars=[]) {
                    $env = \App::make('cms.twig.environment');
                    return $env->createTemplate($content)->render($vars);
                },
            ],
        ];
    }

You can now render any twig content in your markup as shown below:

{{ html_clean(fieldWithTwigContent | twig) }}

Discussion

0 comments

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