Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2/Twig: how to tell the custom twig tag to NOT escape the output

Tags:

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'),
        );
    }
like image 724
stoefln Avatar asked Mar 09 '12 12:03

stoefln


People also ask

Where can we define custom twig functions?

Twig provides a number of handy functions that can be used directly within Templates. Drupal core adds a handful of custom functions that are Drupal-specific. These are defined in the TwigExtension class. You can also define your own custom Twig functions in a custom module (but not in a theme).

What is twig extension?

Twig Extensions allow the creation of custom functions, filters, and more to use in your Twig templates.

What is Twig Environment?

Twig uses a central object called the environment (of class \Twig\Environment ). Instances of this class are used to store the configuration and extensions, and are used to load templates. Most applications create one \Twig\Environment object on application initialization and use that to load templates.


2 Answers

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')
        ))
    );
}
like image 197
Crozin Avatar answered Oct 14 '22 23:10

Crozin


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']
    ]),
];
like image 41
jcroll Avatar answered Oct 14 '22 22:10

jcroll