[英]Routing in Symfony2: optional parameter en four urls for one route
In my Symfony2 application I would like to make four urls possible with one route: 在我的Symfony2应用程序中,我想用一条路线制作四个网址:
My route currently looks like this: 我的路线目前看起来像这样:
report:
pattern: /report/{days}
defaults: { _controller: "AppReportBundle:Report:dayReport", days = null }
The action is defined as: 该行动定义为:
public function dayReportAction($days = null)
{
// my code here
}
This currently makes url 1 and 2 working but in the case of url 3 and 4, I get an error 这当前使url 1和2工作,但在url 3和4的情况下,我收到错误
Route not found
路线未找到
How can I make the parameter "days" optional? 如何使参数“days”可选?
And if the parameter is not provided, how can I allow the /
to be omitted as well? 如果没有提供参数,我怎么能同时省略
/
?
Here's a way to do this 这是一种方法
routing.yml 使用routing.yml
report:
pattern: /report/{days}
defaults: { _controller: "AppReportBundle:Report:dayReport", days: null }
requirements:
days: -?\d+
report_reroute:
pattern: /report/
defaults:
_controller: FrameworkBundle:Redirect:redirect
route: report
permanent: true
Since requirements is a regexp pattern it lets you have a negative number. 由于需求是正则表达式模式,因此您可以使用负数。
The reroute section forces the route /report/
to redirect on /report
重新路由部分强制路由
/report/
重定向/report
You can read about this on: Cookbok Entry - Elnur's Answer 你可以在上面读到: Cookbok Entry - Elnur的答案
With such behaviour, you would have: 有了这样的行为,你会有:
Route | Action | Parameters
------------|------------------------|-------------
/report | dayReportAction | $days = null
/report/ | 301 to /report |
/report/60 | dayReportAction | $days = 60
/report/-4 | dayReportAction | $days = -4
/report/foo | 404 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.