Btw. you do not need to call the setRoot method of the view helper ViewModel.
// Create template resolver
$templateResolver = new Zend\View\Resolver\TemplatePathStack(
[
'script_paths' => [__DIR__ . '/view'],
]
);
// Create renderer
$phpRenderer = new Zend\View\Renderer\PhpRenderer();
$phpRenderer->setResolver($templateResolver);
// Initialize view
$view = new Zend\View\View();
// Attach event listener to add the renderer
$view->getEventManager()->attach(
Zend\View\ViewEvent::EVENT_RENDERER,
static function () use ($phpRenderer) {
return $phpRenderer;
}
);
// Create view model
$viewModel = new Zend\View\Model\ViewModel(['userName' => 'John Doe']);
$viewModel->setTemplate('index');
// Create layout model
$layoutModel = new Zend\View\Model\ViewModel;
$layoutModel->setTemplate('layout');
// Add view model as child to layout
$layoutModel->addChild($viewModel);
// Setting for direct output (is needed if no response has been added)
$layoutModel->setOption('has_parent', true);
// Render
echo $view->render($layoutModel);