Enable Twig-Extensions in Silex revisited

As of 2014 things have changed improved a lot in the Symfony / Silex world, compared to 2011, when i first blogged about twig extensions in Silex.
Things got more easy, yay!

As Composer appeared, installation and autoloading is a breeze nowadays.
I presume here, that you have installed your Silex project via composer.
If so, you can install the twig extensions like this:

Just go to your project folder and run:

composer require twig/extensions:~1.0

and your done with installation and autoloading.

Now to integration and service registration, this also got more easy.

Place this after you have registered the twig service:

$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
$twig->addExtension(new Twig_Extensions_Extension_Text($app));
return $twig;
}));

Thats it, now you can use the text filters in your twig templates:

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

Easy…

Leave a Reply

Your email address will not be published. Required fields are marked *