如何在ZF2中将视图渲染为变量?

In a class file, I am trying to render a .phtml file into a variable and pass the HTML output of that .phtml file to a variable in another ViewModel. How do I do this in ZF2?

The code I have so far is, which doesn't really seem to work:

$layout = new ViewModel();
$layout->setTemplate('myPhtmlFile.phtml');
$layout->setTerminal(true);

$viewModel = new ViewModel();
$viewModel->setVariable('formBody', $layout);

Please see the answer I have provided in the following thread:

This is basically the same:

  • you need the PhpViewRenderer
  • you save the output of the render() function into a variable
  • you pass that variable to a view

However doing this has pretty much only the use-case that's described within the other post. Why do you want to do this? It is highly likely that there's a much better solution to what you're trying to accomplish.