gpt4 book ai didi

symfony - 根据路由注解切换模板

转载 作者:行者123 更新时间:2023-12-02 10:32:17 26 4
gpt4 key购买 nike

我在 Controller 中有以下方法:

/**
* @Route("/add", name="item_add")
* @Route("/edit/{id}", name="item_edit")
* @Template
*/
public function editAction(Request $request, Item $item = null)

此方法加载 edit.html.twig模板,因为操作名称。

是否可以强制使用add.html.twig模板如果 item_add路线匹配且 edit.html.twig如果item_edit匹配吗?

最佳答案

jperovic 提供的答案似乎是正确的,但是,恕我直言,使用路线名称感觉不正确。
可以轻松避免依赖路由名称。

这是一个例子

/**
* @Route("/add", name="item_add")
* @Method({"GET"})
* @Template
*/
public function addAction(Request $request, Item $item = null)
{
if (null === $item) {
$item = new Item;
}

$form = $this->createForm(new ItemType, $item, [
'action' => $this->generateUrl('item_update'), // In your view?
'method' => 'POST'
]);

return [
'form' => $form->createView()
];
}

/**
* @Route("/edit/{id}", name="item_edit")
* @Method({"GET"})
* @Template
*/
public function editAction(Request $request, Item $item)
{
return $this->addAction($request, $item);
}

这样,您将有两个路由做几乎相同的事情,并发送相同的参数

/edit/{id} => edit.html.twig
/add => add.html.twig

关于symfony - 根据路由注解切换模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23807564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com