drtiwd06558 2013-03-05 10:03 采纳率: 100%
浏览 50
已采纳

使用默认占位符的symfony2路由

app/config/routing_dev.yml:

people:
    resource: "@myPeopleBundle/Resources/config/routing.yml"
    prefix:   /people

myPeopleBundle/Resources/config/routing.yml:

people_homepage:
    pattern:  /{name}
    defaults: { _controller: myPeopleBundle:Default:index, name: Foo }

people_homepage2:
    pattern:  /
    defaults: { _controller: myPeopleBundle:Default:index, name: Bar }

myPeopleBundle:Controller:DefaultController.php:

...
public function indexAction($name) {
    return $this->render('myPeopleBundle:Default:index.html.twig', array('name' => $name));
}
...

myPeopleBundle:Default:index.html.twig:

Hello {{ name }}!

web/app_dev.php/people -> Hello Foo!
web/app_dev.php/people/ -> Hello Bar!

Why is it different? The people_homepage route why not match the second (web/app_dev.php/people/) url?

But if I set the prefix to / I get the same output:
web/app_dev.php -> Hello Foo!
web/app_dev.php/ -> Hello Foo!

  • 写回答

1条回答 默认 最新

  • dongshou1991 2013-03-05 10:46
    关注

    If you look appdevUrlMatcher.php you will see something like this:

        // people_homepage
        if (preg_match('#^/people(?:/(?P<name>[^/]++))?$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'people_homepage')), array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DefaultController::indexAction',  'name' => 'Foo',));
        }
    
        // people_homepage2
        if (rtrim($pathinfo, '/') === '/people') {
            if (substr($pathinfo, -1) !== '/') {
                return $this->redirect($pathinfo.'/', 'people_homepage2');
            }
    
            return array (  '_controller' => 'Acme\\DemoBundle\\Controller\\DefaultController::indexAction',  'name' => 'Bar',  '_route' => 'people_homepage2',);
        }
    

    You can see that that the route /people/ can not have no match with people_homepage, but it will be with /people or /people/test

    For what you are doing would make more sense if you change the order of the routes

    people_homepage2:
        pattern:  /
        defaults: { _controller: myPeopleBundle:Default:index, name: Bar }
    
    people_homepage:
        pattern:  /{name}
        defaults: { _controller: myPeopleBundle:Default:index, name: Foo }
    

    With this configuration you will have:

    /people == /people/ ---> people_homepage2

    /people/test ---> people_homepage

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题