我在 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/