Enable Twig-Extensions in Silex

Please have look here for a updated version.

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:

    '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) {
    $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|truncate(200)|raw }}

3 Replies to “Enable Twig-Extensions in Silex”

  1. For me {{ post.content|raw|truncate(200) }} didn’t work. I have to use {{ post.content|truncate(200)|raw }}…

    In your solution i get HTML encoded text :)

Comments are closed.