Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a twig rendered template as part of a JSON response?

Tags:

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?

like image 358
ed209 Avatar asked Nov 06 '12 18:11

ed209


1 Answers

Use $this->renderView() instead.

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

like image 162
Elnur Abdurrakhimov Avatar answered Sep 22 '22 10:09

Elnur Abdurrakhimov