在可选参数注解Symfony2的路线 [英] Symfony2 route in annotations with optional parameters
问题描述
我创建了可选的参数控制这样的路线:
i created a route with optional parameter in controller like this:
/**
* League action
*
* @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
* @Route("/association/{assoc}/{league}/{game}")
* @Template()
*
* @param $assoc
* @param $league
* @param $game
* @return array
*/
public function leagueAction($assoc, $league, $game)
但是,如果我尝试创建与这个命名路线的链接,可选参数被省略:
but if i try to create a link with this named route, the optional parameter is ommitted:
{{ path('league', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}
生成的链接是
/协会/ BVNR / 7
/association/BVNR/7
我想什么?
推荐答案
在下面的定义,
* @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
* @Route("/association/{assoc}/{league}/{game}")
两条路线都与你的行动,第一个(名为联盟
这没有任何默认参数和第二无名一(因为你没'不要再增加name属性),这也没有任何缺省参数。
two routes are related to your action, the first one (named "league"
which doesn't have any default parameter and a second unnamed one (as you didn't add name attribute) which also doesn't have any default parameter.
如何解决...
- 添加
名称
你的第二个路线,并调用它,因为它包含了游戏
参数。 - 将
游戏
参数的默认值,你的第二个路线(因为它是唯一一个有一个游戏
参数。 - (你并不真的需要定义两条路线,看看在
如何提高?我的答案
部分)。
- Add a
name
to your second route and call it as it contains"game"
parameter. - Move the default value of
"game"
parameter to your second route (As it the only one to have agame
parameter. - (You don't really need to define two routes, take a look at the
"How to improve ..."
part of my answer).
试试这个...
* @Route("/association/{assoc}/{league}/{game}", name="league_game", requirements={"league" = "\d+"}, defaults={"game" = null})
虽然你应该叫league_game
而不是联盟
,
{{ path('league_game', {'assoc': association.short, 'league': league.id, 'game': g.id}) }}
如何提高...
请确保你确实需要定义两条路线,因为我建议只保留一条路径。
Make sure you really need to define two routes, because I would suggest keeping only one route.
至于有一个默认值游戏
在下面的定义,
As there's a default value for "game"
in the following definition,
@Route("/association/{assoc}/{league}/{game}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null}
然后,它涵盖了两个版本,有和没有游戏
。
这篇关于在可选参数注解Symfony2的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!