Difference Between $this->renderView and $this->render in Symfony2

renderView(): Returns a rendered view.
render(): It renders full HTTP response (with headers) and returns a Response object (with the rendered template, headers, etc).

For example:
If you have a controller action that generates an XML file from a twig template using render() and serves it to clients like this :
$response = new Response();
$response->setContent($this->render('MyBundle:Formation:feed.xml.twig',
  array('formation' => $formation);
$response->headers->set('Content-Type', 'text/xml');
 
return $response;

but when you save the file on the browser side, It will contain the HTTP headers :
HTTP/1.0 200 OK
Cache-Control: no-cache
Date:          Tue, 18 Oct 2015 12:04:39 GMT

<?xml version="1.0" encoding="UTF-8"?>
(...)
In order to get rid of these headers in the downloaded XML file, you should use renderView() method,
$response = new Response();
$response->setContent($this->renderView('MyBundle:Formation:feed.xml.twig',
  array('formation' => $formation);
$response->headers->set('Content-Type', 'text/xml');
 
return $response;

Comments

Popular Posts