[英]FOSRestBundle: Pass additional variables to the Twig template
I'm using the same action to deal with an html
and a json
response, just suffixing the later one route with .json
. 我正在使用相同的动作来处理
html
和json
响应,只是在后一条路由后缀了.json
。
The json
is working with no problem, but when the response is html
I need to pass an additional variable to the Twig
template, and I don't know and I don't find how to do it. json
正常工作,但是当响应为html
我需要将一个附加变量传递给Twig
模板,我不知道,我也找不到如何做。 At the moment, my code is: 目前,我的代码是:
// $entity = get my data;
$name = 'foo';
$view = $this->view($entity, 200)
->setTemplate('MyBundle:MyController:myTemplate.html.twig')
->setTemplateVar('entity')
;
return $this->handleView($view);
How can I pass $name
to myTemplate.html.twig
? 如何将
$name
传递给myTemplate.html.twig
? What I would need is something like: 我需要的是这样的:
//...
->setTemplate('MyBundle:MyController:myTemplate.html.twig', array('name' => $name))
//...
Ok, I got the response opening an issue in FosRestBundle github page . 好的,我得到了在FosRestBundle github page中打开问题的响应。
At the moment, there is no straightforward way, but the following procedure will work: 目前,还没有直接的方法,但是可以执行以下过程:
1) Add _format
option with html
and json
values, respectively, in the route defaults: 1)在路由默认值中分别添加
html
和json
值的_format
选项:
defaults: { _controller: myBundle:myController:myAction, _format: html } #or json
2) Add $_format
as the first parameter of the action signature: 2)添加
$_format
作为动作签名的第一个参数:
public function myActionAction($_format, $any_other_paramer)
3) Conditionally add more variables to the Twig template: 3)有条件地向Twig模板添加更多变量:
if ($this->get('fos_rest.view_handler')->isFormatTemplating($_format)) {
$view->setData(array('name' => $name, 'entity' => $view->getData()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.