25

I want to return an HTML snippet as well as other values in a json string, here is what I have:

$html = $this->render('sometemplate.html.twig', array( 'somevar' => $somevar ) );
$response = new Response(json_encode( array("html" => $html, "name" => "Joe Bloggs") ));
$response->headers->set('Content-Type', 'application/json');
return $response;

But all I get is {"html":{"headers":{}}}. Is there a way to just grab the rendered HTML?

1 Answer 1

48

Use $this->renderView() instead.

$this->render() returns a Response object, while $this->renderView() returns a string resulting from rendering a template.

2
  • 3
    Just adding that these methods are part of Symfony. The Twig core library uses $twig->display for outputting content, while $twig->render returns the content. Could be a bit confusing! :-)
    – Webberig
    Jul 22, 2013 at 20:50
  • 2
    another way could be the use of getContent() method of the Response object.
    – stef
    Feb 28, 2014 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.