【问题标题】:Zend Framework 2: Composing web page of several partsZend Framework 2:由几个部分组成的网页
【发布时间】:2013-09-21 00:34:22
【问题描述】:

我需要组合几个视图模板的网页(视图模板渲染页面内容和视图模板渲染侧边栏)。在我的 layout.phtml 中,我有两个变量占位符:$content 和 $sidebar:

......
<?php echo $this->sidebar; ?>
......
<?php echo $this->content; ?>
......

在我的控制器的操作中,我通过链接在树中的 ViewModel 将数据传递给这些视图模板:

public function indexAction() {

 // Preparing my data
 // $form = ...
 // $menuItems = 
 // $activeItem =       

 // Create sidebar view model
 $sidebarViewModel = new ViewModel(array('menuItems'=>$menuItems, 'activeItem'=>$activeItem));
 // Add it as a child to layout view model
 $this->layout()->addChild($sidebarViewModel, 'sidebar');

 // Page content view model
 $viewModel = new ViewModel(array('form'=>$form));
 return $viewModel;     
}

但是,因为我在每个页面上都有侧边栏,所以我必须为每个控制器的每个操作复制并粘贴此代码。是否有任何推荐的方法来重用填充侧边栏的 ViewModel 的代码?

【问题讨论】:

标签: php templates zend-framework2


【解决方案1】:

一种方法是使用控制器插件来实现这一点。

假设您已使用适当的配置将其连接起来,并且您位于应用程序模块中。

module/Application/src/Application/Controller/Plugin/AddSidebar.php:

namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class addSidebar extends AbstractPlugin {

    public function __invoke($menu, $active) {

        // create new view model
        $sidebarVM = new ViewModel(array(
            'menuItems'  => $menu,
            'activeItem' => $active
        ));

        // add it to the layout
        $this->getController()->layout()->addChild($sidebarVM, 'sidebar');

    }

}

然后在你的每个控制器中:

$this->addSidebar($menuItems, $activeItem);

另一个(可能更好)选项是连接到渲染MvcEvent 并在那里添加侧边栏。但是,您必须弄清楚如何在这种情况下生成 $menuItems$activeItem

【讨论】:

  • 感谢您的回答!
  • 非常感谢您的回答,如果您能详细解释一下,我们将不胜感激。
  • 您想详细了解设置的哪一部分?
  • 我发现Using Zend Framework 2这本书对这个话题有很好的解释。对初学者来说非常容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2014-05-02
相关资源
最近更新 更多