【发布时间】:2021-07-05 01:34:54
【问题描述】:
我正在尝试更改{{ url('app_route_name') }} or {{ path('app_route_name') }} 的输出。通常输出可能是/app/route/name 我只想修改树枝输出。
我的第一次尝试是装饰 UrlGenerator->generate,但更改 $name 也会更改调用的控制器。我只是想改变最终的输出。
这是我目前正在尝试的代码。我得到的错误异常是:
未知的“路径”功能。您是说“logout_path”、“relative_path”、“impersonation_exit_path”吗?
App\Service\TwigUrlDecorator:
decorates: 'twig.extension.routing'
arguments: ['@.inner']
public: false
// src/Service/TwigUrlDecorator.php
namespace App\Service;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Extension\AbstractExtension;
use Symfony\Bridge\Twig\Extension\RoutingExtension;
class TwigUrlDecorator extends AbstractExtension
{
private $generator;
private $router;
public function __construct(RoutingExtension $router, UrlGeneratorInterface $generator)
{
$this->router = $router;
$this->generator = $generator;
}
public function getPath(string $name, array $parameters = [], bool $relative = false): string
{
return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH);
}
public function getUrl(string $name, array $parameters = [], bool $schemeRelative = false): string
{
return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL);
}
}
我原来的question 可能会为我正在寻找的东西提供一些背景。
【问题讨论】:
-
您应该能够通过注入环境并执行
$env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getUrl($parms)来获得原始输出。然后我会改变那里的输出。 -
看来你还没有完全了解装修。现在将调用您的服务而不是原始服务。而且您的服务不包括树枝函数定义。
-
@yivi 你是对的,我只是在我之前列出的问题中发现了它。我花了一整天的时间研究装饰,但几乎没有发现如何从头到尾做到这一点。只有sn-ps,当我不知道如何合并它时没有帮助......
-
您需要更好地了解装饰是什么,以及如何创建树枝扩展。如果您了解这两个部分,那么接下来的内容就很简单了。 Nico 的回答已经向您展示了您需要添加到装饰器中的内容。这就是你目前所需要的。祝你好运。
-
我已经创建了一个扩展来过滤我的网址,我可能会在多玩一些扩展之后回到这个问题。
标签: php symfony twig decorator