SYMFONY TWIG EXTENSION ESCAPE

TWIG EXTENSION ESCAPE

在使用Symfony有时候会遇到一些状况需要自己去客製化twig的Escape
以下是一个twig escape的範例:

<?phpnamespace AppBundle\Twig;class EscapeExtension extends \Twig_Extension implements Twig_Extension_InitRuntimeInterface{    public function initRuntime(\Twig_Environment $environment)    {        $environment->getExtension('core')->setEscaper('custom', array($this, 'customEscaping'));    }    public function customEscaping(\Twig_Environment $environment, $string, $charset)    {        $string = htmlspecialchars($string);        return $string;    }    public function getName()    {        return 'custom';    }    public function getGlobals()    {        return [];    }}

然后在去service.yml加入

EscapeExtension:    class: AppBundle\Twig\EscapeExtension    public: false    tags:        - { name: twig.extension }

使用时只要

{% autoescape 'custom' %}...{% endautoescape %}

注意
initRuntime在新版的twig已经建议不用了
要使用需要implements Twig_Extension_InitRuntimeInterface
因此这个範例只适合在特殊情况
平常建议使用twig的Filter去处理
且经测试过后 此方法无法使用在symfonyform


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章