The TwigServiceProvider provides integration with the Twig template engine.
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));
Note
Twig comes with the “fat” Silex archive but not with the regular one. If you are using Composer, add it as a dependency to your composer.json file:
"require": {
"twig/twig": ">=1.8,<2.0-dev"
}
Symfony provides a Twig bridge that provides additional integration between some Symfony2 components and Twig. Add it as a dependency to your composer.json file:
"require": {
"symfony/twig-bridge": "2.1.*",
}
When present, the TwigServiceProvider will provide you with the following additional capabilities:
The Twig provider provides a twig service:
$app->get('/hello/{name}', function ($name) use ($app) {
return $app['twig']->render('hello.twig', array(
'name' => $name,
));
});
This will render a file named views/hello.twig.
In any Twig template, the app variable refers to the Application object. So you can access any service from within your view. For example to access $app['request']->getHost(), just put this in your template:
{{ app.request.host }}
A render function is also registered to help you render another controller from a template:
{{ render(app.request.baseUrl ~ '/sidebar') }}
{# or if you are also using UrlGeneratorServiceProvider with the SymfonyBridgesServiceProvider #}
{{ render(url('sidebar')) }}
Note
You must prepend the app.request.baseUrl to render calls to ensure that the render works when deployed into a sub-directory of the docroot.
Silex\Application\TwigTrait adds the following shortcuts:
return $app->render('index.html', ['name' => 'Fabien']);
$response = new Response();
$response->setTtl(10);
return $app->render('index.html', ['name' => 'Fabien'], $response);
// stream a view
use Symfony\Component\HttpFoundation\StreamedResponse;
return $app->render('index.html', ['name' => 'Fabien'], new StreamedResponse());
You can configure the Twig environment before using it by extending the twig service:
$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
$twig->addGlobal('pi', 3.14);
$twig->addFilter('levenshtein', new \Twig_Filter_Function('levenshtein'));
return $twig;
}));
For more information, check out the Twig documentation.