如何将树枝呈现的模板作为 JSON 响应的一部分返回?

2022-01-22 00:00:00 json php symfony twig

我想返回一个 HTML 片段以及 json 字符串中的其他值,这就是我所拥有的:

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;

但我得到的只是 {"html":{"headers":{}}}.有没有办法只抓取呈现的 HTML?

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

推荐答案

使用 $this->renderView() 代替.

$this->render() 返回一个 Response 对象,而 $this->renderView() 返回一个字符串结果从渲染模板.

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

相关文章