RSS Feed
2012/02/22

Enable Twig-Extensions in Silex

Ivo Bathke, 2011/11/21 10:55

Note: its about Twig-extensions not about the former “Silex Twig Extension”, this now called TwigServiceProvider.

First fetch the Twig-extensions code and put them in your vendor dir:

git submodule add git://github.com/fabpot/Twig-extensions.git vendor/Twig-extensions/fabpot
git submodule init
git submodule update

Then register the autoloader by using registerPrefixes:

$app['autoloader']->registerPrefixes(array(
    'Twig_Extensions_'  => array(__DIR__.'/../vendor/Twig-extensions/fabpot/lib')));

You will need to register the TwigServiceProvider itself:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/../views',
    'twig.class_path' => __DIR__ . '/../vendor/twig/lib',
));

And eventually enable the Extension you like to use, in my case the Text Extension to use the truncate filter:

$oldTwigConfiguration = isset($app['twig.configure']) ? $app['twig.configure']: function(){};
$app['twig.configure'] = $app->protect(function($twig) use ($oldTwigConfiguration) {
    $oldTwigConfiguration($twig);
    $twig->addExtension(new Twig_Extensions_Extension_Text());
});

That might look a bit strange but it has its reasons, read here.

Thats it! Now i can use something like this in my twig templates:

{{ post.content|raw|truncate(200) }}

One Response to “Enable Twig-Extensions in Silex”

  1. Christian says:

    Nice one. Like your brief and to-the-point style! :)

Leave a Reply