Using the controller, you can use the controller plugin called Layout to set the variable:
$this->layout()->username = "some value";
Then in layout.phtml you can:
<?php echo $this->username; ?>
If you look at Zend\Mvc\Controller\Plugin\Layout , you will see that the __invoke method will return an instance of ViewModel without parameters, so why does this work.
source share