[英]Symfony2 optional route parameters with keys
In symfony2 routing.yml I am trying to create a route with optional parameters like this: 在symfony2 routing.yml中,我尝试使用以下可选参数创建路由:
/app/type/{typeValue}/page/{page}
So, an example that would work is: 因此,一个可行的示例是:
/app/test/type/hello/page/1
My route is: 我的路线是:
api_test:
pattern: /api/test/type/{typeValue}/page/{page}
defaults: { _controller: TestCoreBundle:Json:test, page:1 }
This is fine but i want to have /type/{typeValue} and /page/{page} optional so it works also for urls like this: 很好,但我想使用/ type / {typeValue}和/ page / {page}可选,因此它也适用于如下网址:
/app/test
/app/test/page/3
/app/test/type/myType
My other routes will also contain more complicated optional parameters so it is important for me to solve this problem. 我的其他路线还将包含更复杂的可选参数,因此对我来说解决此问题很重要。 What do I need to do so that I dont need to create separate routes so it supports every single combination?
我该怎么做,以至于我不需要创建单独的路由,从而支持每个单独的组合?
动态路由参数仍需要填充或默认,我建议将这些参数作为选项传递,然后附加到查询字符串(例如?page = 1&myType = blah),并在控制器的基类中使用$ request-> get()。
As explained on the symfony page everything after an optional placeholder has to be optional too. 如symfony页面上所述,可选占位符之后的所有内容也必须是可选的。
Of course, you can have more than one optional placeholder (eg
/blog/{slug}/{page}
), but everything after an optional placeholder must be optional.当然,您可以有多个可选的占位符(例如
/blog/{slug}/{page}
),但是可选的占位符之后的所有内容都必须是可选的。 For example,/{page}/blog
is a valid path, but page will always be required (ie simply/blog
will not match this route).例如,
/{page}/blog
是有效路径,但是始终需要page(即,简单地/blog
将不匹配此路由)。
In your case {typeValue}
is optional but followed by /page/
which is not optional, so this rout will never work with both parameters optional. 在您的情况下,
{typeValue}
是可选的,但后面是/page/
,后者不是可选的,因此,此路由将无法与两个可选参数一起使用。 You can either use query strings or change your route to something like 您可以使用查询字符串,也可以将路线更改为类似
api_test:
pattern: /api/test/{typeValue}/{page}
defaults: { _controller: TestCoreBundle:Json:test, typeValue: 'default', page: 1 }
requirements:
page: \d+
You will then be able to use routes 然后,您将可以使用路线
/app/test
/app/test/myType
/app/test/myType/3
But even then route /app/test/3
is not possible, since symfony will interpret this as $typeValue = 3
and $page
as default. 但是即使这样,路由
/app/test/3
还是不可能的,因为symfony会将其解释为$typeValue = 3
而$page
是默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.