Winter 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 October 28th, 2023 - Previously published on OctoberTricks

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

Add this twig filter to your Plugin.php:

use Cms\Classes\Controller;

public function registerMarkupTags()
{   
    return [
        'filters' => [
            'twig' => function ($content, $vars=[]) {
                $controller = Controller::getController() ?: new Controller;
                $vars = array_merge($vars, $controller->vars);
                $env = $controller->getTwig();
                return $env->createTemplate($content)->render($vars);
            },
        ],
    ];
}

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

{{ fieldWithTwigContent | twig }}

Discussion

0 comments

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