【问题标题】:Symfony2 routing optional parameter and format path/patternSymfony2 路由可选参数和格式路径/模式
【发布时间】:2013-04-01 12:15:24
【问题描述】:

我想使用单个路由模式构建以下 URI

1 hello/first.format
2 hello/first
3 hello/first/last.format
4 hello/first/last

其中 first 是必需的,lastformat 是可选的。

这是我尝试过的:

hello-route:
  pattern:  /hello/{fist_name}/{last_name}.{_format}
  defaults: { _controller: AcmeHelloBundle:Default:index, last_name:Default, _format:html}
requirements:
  _format: html|rss|json
  first_name: \w+
  last_name: \w+

但不正确,因为它匹配 2、3 和 4 但不匹配 1。1 不会失败,但尽管有要求,它仍会将 {first_name} 匹配为“first.format”。

如何使用基本路由来做到这一点?

【问题讨论】:

    标签: symfony routing pattern-matching


    【解决方案1】:

    定义两条路线来完成此操作

    hello-route-first:
      pattern:  /hello/{fist_name}.{_format}
      defaults: { _controller: AcmeHelloBundle:Default:index, _format:html}
    requirements:
      _format: html|rss|json
      first_name: \w+
    
    hello-route-last:
      pattern:  /hello/{fist_name}/{last_name}.{_format}
      defaults: { _controller: AcmeHelloBundle:Default:index, _format:html}
    requirements:
      _format: html|rss|json
      first_name: \w+
      last_name: \w+
    

    然后将 $last_name 参数设置为控制器中的可选参数

    function indexAction($first_name, $last_name = "")
       {
    

    【讨论】:

      猜你喜欢
      • 2014-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多