Prevent output escaping in Twig function extension

2019-03-22 19:25发布

问题:

I have created a Twig extension:

{{ image ("image.png", 200) }}

HI know I can just do

{{ image ("image.png", 200)|raw }}

...but I would prefer to use PHP code so that everything (from this 'image' extension) is not escaped.

I can't see this possible.

I know I can prevent all output escaping in Twig, but I just want this one extension not to escape output, and everything else to do so.

回答1:

This can be done by adding an option at the extension registration.

public function getFilters(){
    return array(
        // ...
        'image' => new \Twig_Filter_Method($this, 'imageFilter',
            array('is_safe' => array('html'))
        ),
        // ...
    );
}

This will provide unescaped input HTML and return unescaped HTML output. If you need to work with escaped HTML input, see the option 'pre_escaped' => 'html'.



回答2:

For twig function extension do this

public function getFunctions()
{
  return array(
     new \Twig_SimpleFunction(
        'image', 
        array($this, 'image'), 
        array('is_safe' => array('html')))
  );
}


回答3:

I use a function

$twig->addFunction(new \Twig_SimpleFunction('html', function ($code) {
   return new \Twig_Markup($code, "utf-8");
}));
{{ html(myhtmlcode) }}


回答4:

In twig version 2 you can solve it like this:

environment: Symfony 4 and twig-bundle ^4.0

code:

public function getFilters(): array
{
    return [,
        new TwigFilter('image', [$this, 'image'], ['is_safe' => ['html']]),
    ];
}


标签: symfony twig