【发布时间】:2015-09-09 12:03:26
【问题描述】:
使用 ajax 创建一个新元素后,我从我的控制器中获得了一个 JsonResponse。现在我想更新元素列表。因此,我希望将新表作为 JsonResponse 中的变量。
如何在我的控制器动作中呈现模板?
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyBundle:Entity')->find($id);
$em->persist($entity);
$em->flush();
$template = $this->render('MyBundle:Entity:show.html.twig');
return new JsonResponse(array('message' => 'Success!'), 200);
当我添加“模板”行时,我的 jsonresponse 出现错误。实体已正确添加到数据库中。
我的模板。 show.html.twig
<table class="table table-responsive table-hover">
<thead>
<tr>
<th>Titel</th>
<th>Link</th>
</tr>
</thead>
<tbody>
{% for entity in entities %}
<tr>
<td>{{ entity.titel }}</td>
<td>{{ entity.link }}</td>
</tr>
{% endfor %}
</tbody>
</table>
我的电话
$template = $this->render('MyBundle:Entity:show.html.twig', array('entities'=> $entities));
【问题讨论】:
-
$this->render(...将工作。你遇到了什么问题? -
在插入此行后,我收到了一个错误的 JsonResponse。我的路由正确吗?捆绑名称:实体名称:模板名称?我的模板放在 Resources/views/Entityname
-
请发布您遇到的所有相关代码/错误。目前这只是猜测。
$this->render会给你一个字符串(可能是html),这完全取决于你如何进一步使用这个字符串。 -
这个错误还是不见了。
-
我也做过很多次,从来没有遇到过任何问题。不过,我有一种感觉,您可能必须在渲染时将必要的变量传递给
MyBundle:ENtity:show.html.twig。例如$this->render('MyBundle:Entity:show.html.twig', array('entity' => $entity))?同样,出现错误和相关代码会有所帮助,或者我们可以一直猜测。
标签: symfony templates jsonresponse