Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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).

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?

Thanks!

like image 232
Lee Benson Avatar asked Feb 29 '12 18:02

Lee Benson


1 Answers

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;
}));
like image 80
Maerlyn Avatar answered Sep 28 '22 09:09

Maerlyn