使用Silex的树枝添加过滤器 [英] Twig addFilter using Silex?
问题描述
使用Silex时,将自定义过滤器连接到Twig,但保持现有的 twig.options
不变的正确方法是什么?
What's the right way to hook up a custom filter to Twig when using Silex, but keep the existing twig.options
intact?
这就是我的意思。我有以下代码:
Here's what I mean. I have the following code:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => dirname(__FILE__).'/view',
'twig.class_path' => dirname(__FILE__).'/vendor/twig/lib',
'twig.options' => array('cache'=>'folder/twig')
));
function test() {
return 'yay';
}
$app['twig']->addFilter('test',new \Twig_Filter_Function('test'));
如果我按原样运行该代码,则过滤器不起作用。
If I run that code as-is, the filter DOESN'T WORK.
相反,Twig返回了PREVIOUS REQUEST的无限缓存版本(即使我清除了缓存内容-我猜这是因为由于覆盖而将缓存存储在其他位置 twig.options
...不确定)。
Instead, Twig returns an infinitely cached version of the PREVIOUS REQUEST (even if I clear out the cache contents - I'm guessing this is because the cache is being stored elsewhere since I'm overwriting twig.options
... not sure).
但是,如果我放弃以下行:
However, if I ditch the following line:
'twig.options' => array('cache'=>'folder/twig')
...然后一切正常。
... then everything works.
我怎样才能使两者表现得更好?即保留缓存并添加自定义过滤器?
How can I get the two to play nicely? i.e. keep the cache AND add custom filters?
谢谢!
推荐答案
您应该在创建树枝扩展名并在其中添加过滤器。
You should be creating a twig extension and adding your filter there.
#src/Insolis/Twig/InsolisExtension.php (snippet)
<?php
namespace Insolis\Twig;
class InsolisExtension extends \Twig_Extension
{
public function getName() {
return "insolis";
}
public function getFilters() {
return array(
"test" => new \Twig_Filter_Method($this, "test"),
);
}
public function test($input) {
return "yay";
}
}
如何注册:
#app/bootstrap.php
$app["twig"] = $app->share($app->extend("twig", function (\Twig_Environment $twig, Silex\Application $app) {
$twig->addExtension(new Insolis\Twig\InsolisExtension($app));
return $twig;
}));
这篇关于使用Silex的树枝添加过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!