iT邦幫忙

0

SYMFONY TWIG EXTENSION ESCAPE

TWIG EXTENSION ESCAPE

在使用Symfony有時候會遇到一些狀況需要自己去客製化twig的Escape
以下是一個twig escape的範例:

<?php
namespace 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


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言