简体   繁体   English

Symfony2 / Twig:如何告诉自定义twig标签不要逃避输出

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

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? 有没有办法直接在树枝延伸中进行unescape?

My extension registers the thumbnail code like this: 我的扩展程序注册缩略图代码如下:

 public function getFunctions()
    {
        return array(
            'thumbnail' => new \Twig_Function_Method($this, 'thumbnail'),
        );
    }

The third argument of Twig_Function_Method::__construct() is an array of options for the function. Twig_Function_Method::__construct()的第三个参数是函数的选项数组。 One of these options is is_safe which specifies whether function outputs "safe" HTML/JavaScript code: 其中一个选项是is_safe ,它指定函数是否输出“安全”的HTML / JavaScript代码:

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

Crozin's answer is correct but because \\Twig_Function_Method is now deprecated you can use \\Twig_SimpleFunction as such: Crozin的答案是正确的,但因为\\Twig_Function_Method现在已经过时,你可以使用\\Twig_SimpleFunction这样:

return [
    new \Twig_SimpleFunction('thumbnail', [$this, 'thumbnail'], [
        'is_safe' => ['html']
    ]),
];

Twig does it like this: Twig是这样的:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM