0

I was wondering if it is possible or how to be able to define a ViewModel in the Application module and pass it to display in the layout.phtml in Zend Framework 2. Here is the code for the Application Controller:

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $container = new Container('session');

        return new ViewModel(array('username' => $container->username,
                                   'password' => $container->password));
    }
}

 This is the layout.phtml page I am trying to get username to display

 <ul class="nav navbar-nav navbar-right">
   <li><p class="navbar-text" style="font-family: Papyrus, fantasy; font-size: 20px;">       
     <?php echo $username; ?></p></li> 
  </ul> 

Any help would be appreciated.

4

1 回答 1

-1

如果您想在布局 ViewModel 中显示任何称为根 ViewModel 的内容,您应该使用控制器的 layout() 插件:

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $container = new Container('session');
        $mainLayout = $this->layout();
        $mainLayout->setVariable('foo', 'bar'); //it accepts array too 
        return new ViewModel(array('username' => $container->username,
                               'password' => $container->password));
    }
}

在 layout.phtml 中

<?php echo $this->foo ;?> // or just $foo

作为旁注,使用插件和查看帮助程序来显示用户名或其他用户相关的东西,特别是如果您的用户已登录。检查 Zend\Authentication 和插件 identity() 它在 Zend\Mvc\Controller\Plugin\Identity.php 并检查在 Zend\Mvc\Controller\Plugin\Service\IdentityFactory.php 中输出它的工厂

您始终可以制作自己的身份插件并使用您的自定义工厂对其进行自定义。

于 2013-11-01T23:20:50.003 回答