Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I render view without returning it in action controller in zend framework 2?

Now I am doing so:

public function indexAction() {
    ...
    $view = new ViewModel(array(
        'foo' => 'bar',
    ));
    return $view;
}

The problem is that I want to do something after $view rendering and before layout rendering:

public function indexAction() {
    ...
    $view = new ViewModel(array(
        'foo' => 'bar',
    ));
    $layout = $this->layout();

    $layout->content = $view->render();
    ...
    // here I want to do some important action
    ...
    $html = $layout->render();
    return $this->getResponse()->setContent($html);    
}

But there is no method render(). In ZF1 I could render view:

$view = new Zend_View($data);
$html = $view->render($templateName);

How can I do that in ZF2?

like image 756
Ildar Avatar asked Mar 21 '13 22:03

Ildar


2 Answers

Try this:

public function IndexAction()
{
    ...
    $viewRender = $this->getServiceLocator()->get('ViewRenderer');
    $html = $viewRender->render($viewModel);
    ...
}
like image 136
Weteef Avatar answered Nov 22 '22 12:11

Weteef


Complementing the answer, with layout included...

public function IndexAction() {
    ...
    $viewRender = $this->getServiceLocator()->get('ViewRenderer');

    $layout = new ViewModel();
    $layout->setTemplate("layout/main");
    $layout->setVariable("content", $viewRender->render($viewModel));

    $html = $viewRender->render($layout);
    ...
}
like image 25
Ignacio Pascual Avatar answered Nov 22 '22 13:11

Ignacio Pascual