【问题标题】:Symfony2: JSON Response To Twig?Symfony2:对 Twig 的 JSON 响应?
【发布时间】:2012-01-12 11:37:23
【问题描述】:

我从 mongodb 收到一个 json 响应,但我无法将它放入树枝模板中。有人可以解释一下并展示最佳做法吗?谢谢。

/**
 * @Route("/event/{id}", name="event_details_view")
 * @Template()
 */
public function viewAction($id)
{
    $event = $this->get('doctrine.odm.mongodb.document_manager')
        ->getRepository('DungeonEventBundle:Event')
        ->findById($id);

    if (!$event) {
        throw $this->createNotFoundException('Event .$id. was not found.');
    }

    return new Response(json_encode($event));
}

【问题讨论】:

    标签: json mongodb symfony twig


    【解决方案1】:

    首先,您没有收到来自 MongoDB 的 JSON 响应——您收到的是一个 Event 文档对象。如果您想将它传递给 Twig,而不是返回响应,而是返回一个数组(因为您使用的是 @Template 注释:

    return array('event' => $event);
    

    该对象将在您的模板中作为event 访问。

    【讨论】:

    • 我有点困惑。如果我将事件文档作为数组返回到 twig 模板,则会出现错误:Method "eventTitle" for object "Doctrine\ODM\MongoDB\LoggableCursor" does not exist in DungeonEventBundle:Event:view.html.twig at line 4。这里有什么问题? ://
    • 问题是$event不是单个文档,而是文档的集合。使用find()(或findOneById())代替findById()
    【解决方案2】:

    此处描述的最佳做法是使用base.json.twig 模板,如herehere 所述,而不是Response(json_encode($data))

    【讨论】:

      猜你喜欢
      • 2013-05-30
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多