简体   繁体   English

如何通过Timber为Twig制作自定义逃生者?

[英]How can I make a custom escaper for Twig via Timber?

I'm using Twig and Timber within WordPress and I want to make a custom escaper per Twig's documentation. 我正在WordPress中使用Twig和Timber,我想根据Twig的文档制作一个自定义的转义符

$twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setEscaper('csv', 'csv_escaper');

// before Twig 1.26
$twig->getExtension('core')->setEscaper('csv', 'csv_escaper');

However, I'm not sure how to go about doing this when using Timber with it; 但是,我不确定将Timber与之配合使用时该如何做。 I couldn't find any docs on doing this within Timber - is this possible without editing the core files? 我在Timber中找不到有关此操作的任何文档-如果不编辑核心文件,是否可以做到这一点?

As seen in the documentation you could use add_filter to add the escaper, 文档所示,您可以使用add_filter添加转义符,

add_filter( 'timber/twig', function( \Twig_Environment $twig ) {
    $twig->getExtension('Twig_Extension_Core')->setEscaper('csv', 'csv_escaper');
    return $twig;
} );

After trying DarkBee's answer I ended up finding this answer on a similar question where they got the same error I was getting and after using the below code I got the custom filter working: 在尝试了DarkBee的答案之后,我最终在一个类似的问题上找到了这个答案 ,他们得到了与我相同的错误,并且在使用下面的代码后,我使自定义过滤器起作用了:

add_filter('timber/twig', 'blm_add_twig_custom_filters');

function blm_add_twig_custom_filters($twig) {
    $twig->addExtension(new Twig_Extension_StringLoader());
    $twig->addFilter(new Twig_SimpleFilter('e2', 'escape_no_double'));
    return $twig;
}

/* Custom twig/timber escaper so it doesn't double encode html entities */

function escape_no_double($str) {
    return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', false);
}

More can be found here . 这里可以找到更多。

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

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