Question

I try to load Twig-extensions into Silex but get a:

'Twig_Extensions_Extension_Text' not found

I first register Twig-Extensions in the autoloader:

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

Then register Twig:

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

and add the Extension.

$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());
});

Pathes seem to be correct and Twig itself works fine.

Any idea?

Was it helpful?

Solution

The reason is simple. PEAR-convention autoload mappings are defined as "prefix" => "path". You are setting the "Twig_" prefix for the twig extensions, then you register the twig service provider, which will override it, pointing to twig itself.

The solution is to use a prefix other than "Twig_", preferably something more specific. Something like "Twig_Extensions_".

$app['autoloader']->registerPrefix('Twig_Extensions_', __DIR__.'/../vendor/twig-extensions/lib');

That should fix it.

OTHER TIPS

In Silex 1.3 you can use the new extend method of Pimple:

$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
    $twig->addExtension(new \My\Twig\Extension\SomeExtension($app));
    return $twig;
}));

In Silex 2.0, first register the TwigServiceProvider:

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

Then use Twig Customization path

You can configure the Twig environment before using it by extending the twig service

and Twig Extensions installation guide:

$app->extend('twig', function($twig, $app) {
    $twig->addExtension(new Twig_Extensions_Extension_Text());
    return $twig;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top