So far, I have figured out how to return a typical JSON response in Zend Framework 2. First, I added the ViewJsonStrategy
to the strategies
section of the view_manager
configuration. Then, instead of returning a ViewModel
instance from the controller action, I return a JsonModel
instance with all my variables set.
Now that I've figured that piece out, I need to understand how to render a view and return it within that JSON response. In ZF1, I was able to use $this->view->render($scriptName)
, which returned the HTML as a string. In ZF2, the Zend\View\View::render(...)
method returns void
.
So... how can I render an HTML view script and return it in a JSON response in one request?
This is what I have right now:
if ($this->getRequest()->isXmlHttpRequest()) {
$jsonModel = new JsonModel(...);
/* @todo Render HTML script into `$html` variable, and add to `JsonModel` */
return $jsonModel;
} else {
return new ViewModel(...);
}
{"html":"<tr><td>I'm an HTML response</td></tr>"}
. – Thoreau