使用 Silex 的 Twig addFilter?

2022-01-22 00:00:00 caching php symfony twig 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 SilexProviderTwigServiceProvider(), 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')

...然后一切正常.

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

How can I get the two to play nicely? i.e. keep the cache AND add custom filters?

谢谢!

推荐答案

你应该创建一个 twig 扩展并在那里添加你的过滤器.

You should be creating a twig extension and adding your filter there.

#src/Insolis/Twig/InsolisExtension.php (snippet)
<?php

namespace InsolisTwig;

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, SilexApplication $app) {
    $twig->addExtension(new InsolisTwigInsolisExtension($app));

    return $twig;
}));

相关文章