7

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?

2 Answers 2

29

Try this:

public function IndexAction()
{
    ...
    $viewRender = $this->getServiceLocator()->get('ViewRenderer');
    $html = $viewRender->render($viewModel);
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, could you do this including the layout too?
15

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);
    ...
}

1 Comment

Don't use $this->getServiceLocator() inside the controller, it's deprecated and bad practice. Use a factory to inject the ViewRenderer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.