我如何在Symfony2路由中有可选参数

时间:2021-09-04 06:47:54

I have this code below :

我有以下代码:

/**
 * Lists all User entities.
 *
 * @Route("/{cid}",defaults={"cid" = null},name="user")
 * @Template()
 */
public function indexAction($cid=null)
{}

Now if I type site/user/1 then it works, but if I type site/user/ it says:

现在,如果我键入site / user / 1然后它可以工作,但如果我输入site / user /它说:

No route found

How can I have it that both routes work?

我怎么能知道这两条路线都有效?

3 个解决方案

#1


65  

Try to go to site/user (notice no backslash at the end).

尝试去网站/用户(注意最后没有反斜杠)。

Generally it should work, I have relatively similar configuration working.

一般它应该工作,我有相对类似的配置工作。

But if all else fails you can always define multiple routes for same action, i.e.

但如果所有其他方法都失败了,你可以随时为同一行动定义多条路线,即

/**
 * Lists all User entities.
 *
 * @Route("/", name="user_no_cid")
 * @Route("/{cid}", name="user")
 * @Template()
 */
public function indexAction($cid=null)
{

#2


35  

Use a yml file for your routing configuration, and add a default value for id in your routing parameters like this:

使用yml文件作为路由配置,并在路由参数中添加id的默认值,如下所示:

user:
  pattern:   /site/user/{id}
  defaults:  { _controller: YourBundle:Default:index, id: 1 }

See documentation here

请参阅此处的文档

#3


6  

You could also do it with a GET parameter, e.g.

您也可以使用GET参数执行此操作,例如:

/**
 * @param Request $request
 *
 * @return Response
 */
public function displayDetailAction(Request $request) : Response
{
    if ($courseId = $request->query->get('courseId')) {

#1


65  

Try to go to site/user (notice no backslash at the end).

尝试去网站/用户(注意最后没有反斜杠)。

Generally it should work, I have relatively similar configuration working.

一般它应该工作,我有相对类似的配置工作。

But if all else fails you can always define multiple routes for same action, i.e.

但如果所有其他方法都失败了,你可以随时为同一行动定义多条路线,即

/**
 * Lists all User entities.
 *
 * @Route("/", name="user_no_cid")
 * @Route("/{cid}", name="user")
 * @Template()
 */
public function indexAction($cid=null)
{

#2


35  

Use a yml file for your routing configuration, and add a default value for id in your routing parameters like this:

使用yml文件作为路由配置,并在路由参数中添加id的默认值,如下所示:

user:
  pattern:   /site/user/{id}
  defaults:  { _controller: YourBundle:Default:index, id: 1 }

See documentation here

请参阅此处的文档

#3


6  

You could also do it with a GET parameter, e.g.

您也可以使用GET参数执行此操作,例如:

/**
 * @param Request $request
 *
 * @return Response
 */
public function displayDetailAction(Request $request) : Response
{
    if ($courseId = $request->query->get('courseId')) {