7

使用 Silex 时将自定义过滤器连接到 Twig 的正确方法是什么,但保持现有的twig.options完整?

这就是我的意思。我有以下代码:

$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'));

如果我按原样运行该代码,则过滤器不起作用。

相反,Twig 返回 PREVIOUS REQUEST 的无限缓存版本(即使我清除了缓存内容 - 我猜这是因为缓存被存储在其他地方,因为我正在覆盖twig.options......不确定)。

但是,如果我放弃以下行:

'twig.options' => array('cache'=>'folder/twig')

...然后一切正常。

我怎样才能让两个人玩得很好?即保留缓存并添加自定义过滤器?

谢谢!

4

1 回答 1

20

您应该创建一个树枝扩展并在那里添加您的过滤器。

#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;
}));
于 2012-02-29T21:19:52.740 回答