自动传递路径参数 [英] Pass path parameters automatically

查看:29
本文介绍了自动传递路径参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个网站,用户可以在其中选择他想要的国家、州和城市.

I'm building a site where the user can choose a country, state and city he wants.

一旦他选择了这些参数,他就会进入如下页面:en.example.com/spain/madrid/madrid/

Once he selects these parameters he goes to a page like this: en.example.com/spain/madrid/madrid/

问题是,每次我想构建一个新的 url 时,我都必须传递这 3 个变量,我想知道我是否可以做些什么来使它们就像 symfony 本身的 _locale 变量一样将其传递给参数.

The problem is, every time I want to build a new url, I must pass these 3 variables and I was wondering if I could do something to make them just like the _locale variable which symfony itself passes it to the parameters.

谢谢

推荐答案

在搜索更多之后我找到了这篇文章:http://blog.viison.com/post/15619033835/symfony2-twig-extension-switch-locale-current-route

After searching more I found this post: http://blog.viison.com/post/15619033835/symfony2-twig-extension-switch-locale-current-route

我只是使用了这个想法并进行了我需要的更改,这是我的扩展程序的最终代码

I just used the idea and made the changes I needed and this is the final code for my extension

<?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';
    }

}

至于配置和帖子一样

services:
    twig.localized_route_extension:
        class: Acme\CoreBundle\Twig\PathExtension
        tags:
            - { name: twig.extension }
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        arguments: [@router]

对于我使用国家、州和城市的路线,我将它们放在前缀中以避免在每条路线中重复它们.

And for the routes that I use country, state and the city I put them in the prefix to avoid repeating them in each route.

acme_core:
    resource: "@AcmeCoreBundle/Controller/"
    type:     annotation
    prefix:   /{country}/{state}/{city} 

希望能帮到别人.

这篇关于自动传递路径参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆