Zend Framework 2: Modify details of layout.pthml in controllers

layout, model-view-controller, zend-framework2

Solution

From a controller you can use the controller plugin called “Layout” to set a variable:

$this->layout()->username = “some value”;

Then in layout.phtml you should be able to do:

<?php echo $this->username; ?>

If you take a look at `Zend\Mvc\Controller\Plugin\Layout` you will see that the `__invoke` method with no parameters will return an instance of `ViewModel`, hence why this works.

Problem

When I study skeleton application of `Zend Framework 2`, I want to add a label at upper-right of page to show the `UserName` who have logged in. But, I am confused at the code of the navigation bar that was defined in `layout.pthml`,how can controller communicate with the `layout.phtml` to modify it? Thanks in advance! Furthermore, I want a login form upper-right of page when user not logged in using a helper.But i don't know how to add a form using helper,what should i do?

Original source