getherbert / herbert

The WordPress Plugin Framework:
http://getherbert.com/
632 stars 94 forks source link

How I can render a view and send the view via JSON response? #106

Closed giwrgos88 closed 8 years ago

giwrgos88 commented 8 years ago

Hello, I did a controller that is called via a route. Using the ajax I'm calling that controller to add new data on the database and then return an html table row with the data that have been added to the database, via json response.

I did the following

$activity = Activities::find($activity["activity_id"]);
$returnHTML = view('@AdminViews/edit/timeline_partials/timeline-row.twig',compact('activity'));

then I tried the return new JsonResponse($returnHTML) but also the return new JsonResponse($returnHTML->getBody()) but both didn't work. Then I replaced the new JsonResponse with json_response($returnHTML) or json_response($returnHTML->getBody()) but the same result. Then I did json_response($activity) and It work, it sends back a JSON object. Is there any way that I can render the view and then send it back as a json response? Laravel has like the following

$returnHTML = view('job.userjobs')->with('userjobs', $userjobs)->render();
return response()->json(array('success' => true, 'html'=>$returnHTML));
ConnorVG commented 8 years ago

You do it exactly as in Laravel, you can't just send a string as a JSON response (as you've tried in the Herbert example), you must send something JSONable. Like an associative array (as you've shown in the Laravel example).

$activity = Activities::find($activity["activity_id"]);
$html = view('@AdminViews/edit/timeline_partials/timeline-row.twig',compact('activity'));

return new JsonResponse(['success' => true, 'html' => $html]);

😃

giwrgos88 commented 8 years ago

I found the solution right now. Inside @AdminViews/edit/timeline_partials/timeline-row.twig I'm having the following include {% include '@AdminViews/edit/timeline_partials/timeline-row-'~ activity.timeline_meta_key ~ '.twig' %} therefore it wasn't working so I did it like https://github.com/getherbert/example-plugin/blob/master/app/MetaBoxes/ExtendPublish.php#L75-77

$returnHTML =  herbert('twig')->render('@AdminViews/edit/timeline_partials/timeline-row.twig', [
    'activity' => $activity,
 ]);
ConnorVG commented 8 years ago

Yeah, I believe you have to call ->render() on the view object. Apologies.