Symfony总是包含路由默认值

huangapple go评论69阅读模式
英文:

Symfony Always Include Route Default Values

问题

我正在尝试实现以下内容:

我有一个名为task的实体,它有多个状态,如newopenclosed

因此,我试图生成一个路由/tasks/new/tasks/open/tasks/closed。但是,如果在我的路由中没有设置选项,我希望它使用new作为默认值,并将其添加到URL中。

我的控制器:

/**
 * @Route("/tasks/{!status?new}", name="app_tasks")
 */
public function tasks(TaskRepository $taskRepository, string $status)
{
    $tasks = $taskRepository->findBy(['status' => $status]);
    return $this->render('tasks/index.html.twig', ['tasks' => $tasks]);
}

然而,这导致没有一个匹配的路由。

/tasks/new  => 找不到路由  => 应该工作
/tasks/open => 找不到路由  => 应该工作
/tasks      => 找不到路由  => 应该工作,路由应该是/tasks/new
等等。

主要问题似乎是status前面的!。如果完全删除它,一切都按预期工作,只是new任务的路由看起来像/tasks而不是我实际想要的/tasks/new

我已经尝试过清除缓存,但没有成功。Symfony版本是4.4.2。

英文:

So basically I am trying to achieve this: New in Symfony 4.3: Always Include Route Default Values

I have a task entity, which has multiple states like new, open & closed.

For this reason I am trying to generate a route /tasks/new /tasks/open /tasks/closed.
However, if there is no option set in my route, I want it to use new as default and also add it to the url.

My controller:

/**
 * @Route("/tasks/{!status?new}", name="app_tasks")
 */
public function tasks(TaskRepository $taskRepository, string $status)
{
    $tasks = $taskRepository->findBy(['status' => $status]);
    return $this->render('tasks/index.html.twig', ['tasks' => $tasks]);
}

However this results into not a single matching route.

/tasks/new  => no route found  => should work
/tasks/open => no route found  => should work
/tasks      => no route found  => should work & route should be /tasks/new
etc.

The main issue seems to be the ! before status. If I remove it entirely, everything works as expected, except that the route for new tasks looks like /tasks and not like /tasks/new - what I actually want.

I already tried to clear my cache - not working though. Symfony version is 4.4.2.

答案1

得分: 2

github上有一个未解决的问题。
这可能会在新版本中修复。

目前尝试使用以下内容:

@Route("/tasks/{!status}", name="app_tasks", defaults={"status": "new"})
英文:

There is an open issue on github.
This will likely be fixed in newer releases.

As for now try using the following:

@Route("/tasks/{!status}", name="app_tasks", defaults={"status": "new"})

答案2

得分: -2

也许您可以为相同的方法使用2个路由。一个带有slug,一个默认情况下如果未捕获。

或者您可以在控制器中使用基本的if来根据主要问题的slug进行检查。

英文:

Perhaps you can use 2 routes for the same method. One with the slug, one by default if not caught.

Or you can check with a basic if in the controller depending on the slug of your main issues .

huangapple
  • 本文由 发表于 2020年1月3日 19:09:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定