Symfony 自动传递路径参数
我正在建立一个网站,用户可以选择一个国家,州和城市,他想要的 一旦他选择了这些参数,他就会进入这样一个页面:Symfony 自动传递路径参数,symfony,Symfony,我正在建立一个网站,用户可以选择一个国家,州和城市,他想要的 一旦他选择了这些参数,他就会进入这样一个页面:en.example.com/spain/madrid/madrid/ 问题是,每次我想构建一个新的url时,我都必须传递这3个变量,我想知道我是否可以做些什么使它们像symfony本身传递给参数的\u locale变量一样 谢谢在搜索更多信息后,我找到了以下帖子: 我只是使用了这个想法,做了我需要的更改,这是我扩展的最终代码 <?php namespace Comehoy\Cor
en.example.com/spain/madrid/madrid/
问题是,每次我想构建一个新的url时,我都必须传递这3个变量,我想知道我是否可以做些什么使它们像symfony本身传递给参数的\u locale
变量一样
谢谢在搜索更多信息后,我找到了以下帖子: 我只是使用了这个想法,做了我需要的更改,这是我扩展的最终代码
<?php
namespace Comehoy\CoreBundle\Twig\Extension;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
class PathExtension extends \Twig_Extension
{
private $request;
private $router;
public function __construct(Router $router) {
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event) {
if ($event->getRequestType() === HttpKernel::MASTER_REQUEST) {
$this->request = $event->getRequest();
}
}
public function getFunctions()
{
return array(
'l10n_path' => new \Twig_Function_Method($this, 'getPath')
);
}
public function getPath($name, $parameters = array())
{
$parameters = array_merge($parameters, [
'country' => $this->request->get('country'),
'state' => $this->request->get('state'),
'city' => $this->request->get('city'),
]);
return $this->generator->generate($name, $parameters, false);
}
public function getName()
{
return 'twig_my_path_extension';
}
}
对于我使用国家、州和城市的路线,我将它们放在前缀中,以避免在每条路线中重复它们
acme_core:
resource: "@AcmeCoreBundle/Controller/"
type: annotation
prefix: /{country}/{state}/{city}
希望它能帮助其他人。非常感谢您的帮助!在symfony 2.5中,
$this->generator->generate
应该是$this->router->generate
acme_core:
resource: "@AcmeCoreBundle/Controller/"
type: annotation
prefix: /{country}/{state}/{city}