如果我有一批看起来像这样的路线:
/{location}/catalog
/{location}/search
等等
会话始终具有“位置”属性(自动识别用户位置的别名,例如城市)。所以,要生成带有 {location} 参数的每条路线,我需要做
{ location: session.get('location') }
有没有办法自动做到这一点?我可以覆盖默认 UrlGenerator 并将@session 注入其中吗?
尝试覆盖 RoutingExtension 类 /vendor/symfony/symfony/src/Symfony/Bridge/Twig/Extension/CodeExtension.php Symfony 2.1 扩展核心类
您也可以分叉https://github.com/symfony/TwigBridge并将其与作曲家http://getcomposer.org/doc/05-repositories.md#vcs一起使用
像这样创建一个新的 EventSubscriber .. 这个文档类似于https://symfony.com/doc/current/session/locale_sticky_session.html
// src/EventSubscriber/LocationSubscriber.php
class LocationSubscriber implements EventSubscriberInterface
{
private $router;
private $defaultLocation;
public function __construct(string $defaultLocation = "Vigo", RequestContextAwareInterface $router = null)
{
$this->router = $router;
$this->defaultLocation = $defaultLocation;
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the location has been set as a _location routing parameter
if ($location = $request->attributes->get('_location')) {
$request->getSession()->set('_location', $location);
} else {
// if no explicit location has been set on this request, use one from the session
$location = $request->getSession()->get('_location', $defaultLocation);
}
// set Router Context from session
if (null !== $this->router) {
$this->router->getContext()->setParameter('_location', $location);
}
}
public static function getSubscribedEvents(){
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}