Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 297
zc1415926 Avatar asked Sep 23 '12 06:09

zc1415926


2 Answers

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.

like image 191
DrBeza Avatar answered Sep 21 '22 20:09

DrBeza


If you want to define it module-wide, on your Module.php

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

and on your layout.phtml

echo $layout->username;
like image 22
eli_daxs Avatar answered Sep 18 '22 20:09

eli_daxs