Symfony2 中的路由:可选参数 en 一个路由的四个 url [英] Routing in Symfony2: optional parameter en four urls for one route
问题描述
在我的 Symfony2 应用程序中,我想通过一条路线使四个 url 成为可能:
In my Symfony2 application I would like to make four urls possible with one route:
- a-lot-of-other-stuff/report/-20 (负数)
- a-lot-of-other-stuff/report/40 (正数)
- a-lot-of-other-stuff/report/(没有数字)
- 很多其他东西/报告(没有数字也没有/)
我的路线目前是这样的:
My route currently looks like this:
report:
pattern: /report/{days}
defaults: { _controller: "AppReportBundle:Report:dayReport", days = null }
动作定义为:
public function dayReportAction($days = null)
{
// my code here
}
这当前使 url 1 和 2 工作,但在 url 3 和 4 的情况下,我收到错误
This currently makes url 1 and 2 working but in the case of url 3 and 4, I get an error
未找到路线
如何使参数days"可选?
如果没有提供参数,我如何允许 /
也被省略?
How can I make the parameter "days" optional?
And if the parameter is not provided, how can I allow the /
to be omitted as well?
推荐答案
这是一种方法
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
由于 requirements 是一个正则表达式模式,它让你有一个负数.
Since requirements is a regexp pattern it lets you have a negative number.
重新路由部分强制路由 /report/
重定向到 /report
您可以在以下位置阅读:Cookbok Entry - Elnur 的回答
The reroute section forces the route /report/
to redirect on /report
You can read about this on: Cookbok Entry - Elnur's Answer
如果有这样的行为,你会:
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 |
这篇关于Symfony2 中的路由:可选参数 en 一个路由的四个 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!