Silex - Twig_Error_Syntax: The function "path" does not exist Silex - Twig_Error_Syntax: The function "path" does not exist symfony symfony

Silex - Twig_Error_Syntax: The function "path" does not exist


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.


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


Four easy steps.

  1. Create the loader
  2. Create the twig object.
  3. Create you custom function
  4. Add to the Twig object.
    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);