Home » Php » php – Twig addFilter using Silex?

php – Twig addFilter using Silex?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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!

How to&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;
}));