1

i'm getting a json response from mongodb, but i can't get this into a twig template. could somebody explain it and show best pratice? thanks.

/**
 * @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));
}
Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
varg
  • 3,446
  • 1
  • 15
  • 17

2 Answers2

1

First of all, you are not getting a JSON response from MongoDB — you are getting an Event document object. If you want to pass it to Twig, instead of returning a response, return an array (since you're using the @Template annotation:

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

The object will be accessible in your template as event.

Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • I'm a little bit confused. if i return the event document as an array to the twig template i'm getting an error: `Method "eventTitle" for object "Doctrine\ODM\MongoDB\LoggableCursor" does not exist in DungeonEventBundle:Event:view.html.twig at line 4`. what's wrong here? :/ – varg Dec 04 '11 at 15:47
  • The problem is that `$event` is not a single document, but a collection of documents. Use `find()` (or `findOneById()`) instead of `findById()`. – Elnur Abdurrakhimov Dec 04 '11 at 16:26
0

The best practice describe here would be to use a base.json.twig template, as described here and here, instead of Response(json_encode($data)).

Community
  • 1
  • 1
svassr
  • 5,538
  • 5
  • 44
  • 63