Reputation: 26554
According to the Silex documentation:
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.
I include the following in my composer.json
file:
{
"require": {
"silex/silex": "1.*",
"twig/twig": ">=1.8,<2.0-dev",
"symfony/twig-bridge": "2.3.*"
}
}
I register the TwigServiceProvider()
like so:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__ . '/views'
));
I'm attempting to use the twig path()
method like so:
<a href="{{ path('logout') }}">Log out</a>
The error I get is as follows:
Twig_Error_Syntax: The function "path" does not exist
Why am I getting this error?
app.url_generator.generate
in all my templates insteadEnsure The UrlGeneratorServiceProvider()
is registered:
$app->register(new UrlGeneratorServiceProvider());
Create a new function for twig for path()
:
$app['twig']->addFunction(new \Twig_SimpleFunction('path', function($url) use ($app) {
return $app['url_generator']->generate($url);
}));
I shouldn't have to do this!! How can I get this working properly?
Upvotes: 13
Views: 7982
Reputation: 214
Four easy steps.
use Twig\Environment; use Twig\TwigFunction; use Twig\Loader\FilesystemLoader; $loader = new FilesystemLoader('/twig/templates'); $twig = new Environment($loader, []); $function = new TwigFunction('url', function () { return 'MyURL'; }); $twig -> addFunction($function);
Upvotes: 0
Reputation: 2089
I too had to create a new function for twig for path()
, but I improved it a bit to handle a variable number of arguments to allow passing arrays in the twig template:
$app['twig']->addFunction(new \Twig_SimpleFunction('path', function(...$url) use ($app) {
return call_user_func_array(array($app['url_generator'], 'generate'), $url);
}));
Upvotes: 0
Reputation: 26554
Hopefully this will help future viewers as many have posted this question without a solid answer, so here is one.
It is literally that you need UrlGeneratorServiceProvider()
registered
$app->register(new UrlGeneratorServiceProvider());
Also, as umpirsky mentions in the comments, you need symfony/twig-bridge
installed via composer.
You do not need to add your own function. You need both the TwigServiceProvider()
and the UrlGeneratorServiceProvider()
registered before loading your twig template. This isn't easily apparent from the documentation.
Upvotes: 15