Silex - Twig_Error_Syntax: The function “path” does not exist

独自空忆成欢 提交于 2019-12-05 01:26:44

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!