How to render ZF2 view within JSON response?

Answer

public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest()) {
return array();
}

$htmlViewPart = new ViewModel();
$htmlViewPart->setTerminal(true)
->setTemplate('model/controller/action')
->setVariables(array(
'key' => 'value'
));

$htmlOutput = $this->getServiceLocator()
->get('viewrenderer')
->render($htmlViewPart);

$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));

return $jsonModel;
}

Now, we will grab the view renderer with all the template mapping intact and simply render the ViewModel directly. The only important factor is that you need to specify the fully qualified template to render (e.g.: "$module/$controller/$action")
Response looks like this:
Object:
html: "<h1>Hello World</h1>"
jsonArray: Array[6]
jsonVar1: "jsonVal2"

All zend Framework 2 Questions

Ask your interview questions on zend-framework-2

Write Your comment or Questions if you want the answers on zend-framework-2 from zend-framework-2 Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---