вместо этого метода: Как визуализировать представление ZF2 в ответе JSON? который находится в контроллере, я хотел бы автоматизировать процесс, переместив его в событие
У меня есть стратегия в моем модуле.config.php:
Код: Выделить всё
'strategies' => array(
'ViewJsonStrategy',
)
Код: Выделить всё
$events->attach(MvcEvent::EVENT_RENDER, function ($e) use ($controller) {
$controller->setRenderFormat($e);
}, -20);
Теперь я хотел бы изменить рендеринг страницы на основе !$this->getRequest()->isXmlHttpRequest(), (прокомментировано вышел на отладку)
Код: Выделить всё
public function setRenderFormat($e)
{
//if(!$this->getRequest()->isXmlHttpRequest())
//{
$controller = $e->getTarget();
$controllerClass = get_class($controller);
//Get routing info
$controllerArr = explode('\\', $controllerClass);
$currentRoute = array(
'module' => strtolower($controllerArr[0]),
'controller' => strtolower(str_replace("Controller", "", $controllerArr[2])),
'action' => strtolower($controller->getEvent()->getRouteMatch()->getParam('action'))
);
$view_template = implode('/',$currentRoute);
$viewmodel = new \Zend\View\Model\ViewModel();
$viewmodel->setTemplate($view_template);
$htmlOutput = $this->getServiceLocator()->get('viewrenderer')->render($viewmodel, $viewmodel);
$jsonModel = new JsonModel();
$jsonModel->setVariables(array(
'html' => $htmlOutput,
'jsonVar1' => 'jsonVal2',
'jsonArray' => array(1,2,3,4,5,6)
));
return $jsonModel;
//}
}
p.s Есть ли лучший способ реализовать всю концепцию?
p.p.s как мне получить текущий шаблон представления изнутри контроллера, не прибегая к 8 строкам кода?
Заранее спасибо!
Аборгрова
Подробнее здесь: https://stackoverflow.com/questions/169 ... json-model
Мобильная версия