Zend Framework 2: changing layout.pthml details in controllers

When I study the Zend Framework 2 skeleton application, I want to add a label in the upper right corner of the page to show the UserName that are logged in. But I'm confused by the code in the code that was defined in layout.pthml , how can a controller interact with layout.phtml to change it?

Thanks in advance!

Also, I need a login form at the top of the page when the user is not logged in using the assistant. But I don’t know how to add a form using an assistant, what should I do?

+6
source share
3 answers

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.

+7
source

If you want to define it throughout the module, on your Module.php

 public function onBootstrap(MvcEvent $e) { .... $e->getViewModel()->setVariable('username', 'some_value'); } 

and on your .phtml layout

 echo $layout->username; 
+1
source

In module.php u can do this

 public function onBootstrap(MvcEvent $e) { .... $e->getViewModel()->setVariable('username', $username); } 

And in your layout you can do

 echo $this->layout()->username; 

Also check if u used the MvcEvent class.

0
source

Source: https://habr.com/ru/post/926035/


All Articles