I'm using Silex and trying to use the Intl
extension for Twig, but I get the following error when trying to use the localizeddate
filter:
The filter "localizeddate" does not exist in "games.html"
As per these instructions, my composer.json
contains the following line in the require
section:
"twig/extensions": "~1.1.0"
My app.php
file contains this:
$app->register(new TwigServiceProvider(), array(
'twig.path' => __DIR__ . '/../templates/'
));
$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
$twig->addExtension(new Twig_Extensions_Extension_Intl($app));
return $twig;
}));
Finally, somewhere in my games.html
template is this, which throws the error described above:
{{ game.start_time|localizeddate('medium', 'none', 'fr') }}
For the sake of testing, I also tried with the Text
extension, exactly as in the linked instructions, but it generated the same kind of error.
The strange thing is I can put anything in the function where I add the extension; it will never generate any error as long as the syntax is valid. So, if I replace $twig->addExtension(new Twig_Extensions_Extension_Intl($app))
by $twig->addExtension(new Foo())
, Silex doesn't seem to have a problem with it, even though the class Foo
doesn't exist.
If I throw a RuntimeException
in the constructor of the Twig_Extensions_Extension_Intl
class, it doesn't show up either, so it seems the extension is never loaded in the first place. This line can be found in the autoload_namespaces.php
file though: 'Twig_Extensions_' => array($vendorDir . '/twig/extensions/lib')
.
I tried adding a basic Twig_SimpleFilter
the same way, it doesn't work either, so it seems the way I'm trying to add this is just plain wrong, yet it's the way I find everywhere...
The twig service is being redefined later on in the application boot process. (See question comments for debugging steps). The first time twig is being created, you are extending it and adding the extension. Later on, twig is getting defined again, but this time no extension is added.
The second definition overrides the first which is the primary problem. The confusing part is that the original extension never gets called. This is because Silex doesn't actually call your extension function until the twig service is used. Since you are overriding it before that happens, the extension function is never called. To debug, you called $app['twig']
immediately after you defined twig the first time and ensured the extension got run. Through the process of elimination, that means that the twig service is getting overridden sometime later. You determined that that is in the config file.