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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算