简体   繁体   English

使用Silex的枝条addFilter吗?

[英]Twig addFilter using Silex?

What's the right way to hook up a custom filter to Twig when using Silex, but keep the existing twig.options intact? 使用Silex时,将自定义过滤器连接到Twig的正确方法是什么,但保持现有的twig.options不变?

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. 如果我按原样运行该代码,则过滤器不起作用。

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). 取而代之的是,Twig返回了PREVIOUS REQUEST的无限缓存版本(即使我清除了缓存内容-我猜这是因为缓存被存储在其他地方,因为我正在覆盖twig.options ...不确定)。

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? 我怎样才能使两个人打得更好? ie keep the cache AND add custom filters? 即保留缓存并添加自定义过滤器?

Thanks! 谢谢!

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";
    }
}

How to register it: 如何注册:

#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;
}));

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

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