带有可选参数的注释中的 Symfony2 路由 [英] Symfony2 route in annotations with optional parameters

查看:27
本文介绍了带有可选参数的注释中的 Symfony2 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中创建了一个带有可选参数的路由,如下所示:

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}) }}

结果链接是

/association/BVNR/7

/association/BVNR/7

我错过了什么?

推荐答案

在以下定义中,

* @Route("/association/{assoc}/{league}", name="league", requirements={"league" = "\d+"}, defaults={"game" = null})
* @Route("/association/{assoc}/{league}/{game}")

两条路线与您的操作有关,第一个(名为 "league" 没有任何默认参数,第二个未命名的(因为您没有添加 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.

如何解决...

  • name 添加到您的第二条路线并调用它,因为它包含 "game" 参数.
  • "game" 参数的默认值移动到您的第二条路线(因为它是唯一具有 game 参数的路线.
  • (您实际上并不需要定义两条路线,请查看我回答中的如何改进..." 部分).
  • 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 a game 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" 而不是 "league"

While you should call "league_game" instead of "league",

{{ 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.

由于在下面的定义中 "game" 有一个默认值,

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}

然后它涵盖了两个版本,有和没有 "game".

It then covers both versions, with and without "game".

这篇关于带有可选参数的注释中的 Symfony2 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆