I’m using the same action to deal with an html and a json response, just suffixing the later one route with .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. 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? 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.
At the moment, there is no straightforward way, but the following procedure will work:
1) Add
_formatoption withhtmlandjsonvalues, respectively, in the route defaults:2) Add
$_formatas the first parameter of the action signature:3) Conditionally add more variables to the Twig template: