Symfony2/Twig: how to tell the custom twig tag to NOT escape the output
10,806
Solution 1
The third argument of Twig_Function_Method::__construct()
is an array of options for the function. One of these options is is_safe
which specifies whether function outputs "safe" HTML/JavaScript code:
public function getFunctions()
{
return array(
'thumbnail' => new \Twig_Function_Method($this, 'thumbnail', array(
'is_safe' => array('html')
))
);
}
Solution 2
Crozin's answer is correct but because \Twig_Function_Method
is now deprecated you can use \Twig_SimpleFunction
as such:
return [
new \Twig_SimpleFunction('thumbnail', [$this, 'thumbnail'], [
'is_safe' => ['html']
]),
];
Solution 3
Twig does it like this:
class Twig_Extension_Escaper extends Twig_Extension
{
...
public function getFilters()
{
return array(
new Twig_SimpleFilter('raw', 'twig_raw_filter', array('is_safe' => array('all'))),
);
}
...
}
...
function twig_raw_filter($string)
{
return $string;
}
Author by
stoefln
I'm a passionate programmer and designer, currently especially interested in Electron, JS, Android and Arduino.
Updated on June 17, 2022Comments
-
stoefln almost 2 years
I created a custom tag which should work like that:
{{ thumbnail(image.fullPath,620) }}
unfortunately I have to use it like that
{{ thumbnail(image.fullPath,620)|raw }}
Is there a way to unescape directly in the twig extension?
My extension registers the thumbnail code like this:
public function getFunctions() { return array( 'thumbnail' => new \Twig_Function_Method($this, 'thumbnail'), ); }
-
Steve Hill about 11 yearsThanks for that. Is this specified in the documentation? I couldn't find it, but perhaps I didn't look hard enough.
-
acme over 10 years@StephenOrr see the link in Crozin's answer.
-
user1954544 over 10 yearsthank you, it helped me $) can you add link to manual for this? want to know what more then 'html' options can be