Can I render view without returning it in action c

2020-06-04 05:45发布

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条回答
不美不萌又怎样
2楼-- · 2020-06-04 06:07

Try this:

public function IndexAction()
{
    ...
    $viewRender = $this->getServiceLocator()->get('ViewRenderer');
    $html = $viewRender->render($viewModel);
    ...
}
查看更多
放我归山
3楼-- · 2020-06-04 06:14

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);
    ...
}
查看更多
登录 后发表回答