Impossible to pass the router service to a twig extension in symfony 2.6

非 Y 不嫁゛ 提交于 2019-12-06 01:04:51

The Twig environment is available to \Twig_SimpleFunction instances as well as \Twig_SimpleFilter in the same way, though the Twig docs only show it for filters. From the environment, you can get the routing extension like this:

/**
 * {@inheritdoc}
 */
public function getFunctions(): array
{
    return array(
        new \Twig_SimpleFunction('get_my_link_thing', array($this, 'getMyLinkThing'), array('needs_environment' => true)),
    );
}

/**
 * Get something with a generated link.
 *
 * @return string
 */
public function getMyLinkThing(\Twig_Environment $env): string
{
    $targetUrl = $env->getExtension('routing')->getPath('my_route_name');

    return sprintf('Link is <a href="%s">here</a>!', $targetUrl);
}

There are lots of other nifty things in that $env - it's worth trying dump(get_class_methods($env)); and then dumping the results of calling anything in there that strikes your fancy.

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