3

I've created a bolt extension which provides a new twig function foo. The twig functions is added to the twig framework with the following code $this->addTwigFunction('foo', 'twigFoo');.

    public function twigFoo()
    {
        $markup = '
        <hr>
            Foo
        <hr>';

        return new \Twig_Markup($markup, 'UTF-8');
    }

My idea was that the users of the cms can use the twig function in the content types. But when the body of a record is displayed the twig function is visible as plain HTML for example: {{ foo }}

I think the problem is, that the twig template will be rendered before the record body will be assigned. So the body of my record will not be evaluated by twig. Has anyone a idea how to evaluate the twig function witch is use in a record? What's the best practice for this problems?

David
  • 4,027
  • 10
  • 50
  • 102

2 Answers2

4

The field in the ContentType needs allowtwig: true to tell Bolt that you trust the field/editor to allow this, e.g.:

body:
  type: html
  allowtwig: true
Gawain
  • 1,568
  • 10
  • 8
  • Thanks. One more thing to do: The extension must implement the isSafe() function and return true otherwise the allowtwig tag are not evaluating the twig functions from extensions. – David Mar 13 '16 at 03:01
1

The Problem is that Twig does not render Twig inside a Twig variable. You could create an escape function to still do that. Anyway this might not be the best idea to give your CMS users the possibility to use Twig as this gives them full access to your code. Anyway, here is an escape function that could help you

$this->app['twig']->getExtension('core')->setEscaper('code', function($twigEnv, $string, $charset) {
    $twig = clone $this->app['twig'];
    $twig->setLoader(new \Twig_Loader_String());
    return $twig->render($string);
}); 

You could then use the twig filter "code" in your template. e.g.:

{{ record.body|escape('code') }}
MaxiNet
  • 1,008
  • 2
  • 14
  • 22