2013-03-11 75 views
3

在我的应用程序的每个模块中,我将有一个主要内容部分和一个侧边栏菜单。Zend Framework 2两个模板在一个布局中?

在我的布局,我有以下...

<div id="main" class="span8 listings"> 
    <?php echo $this->content; ?> 
</div> 

<div id="sidebar" class="span4"> 
    <?php echo $this->sidebar; ?> 
</div> 

我的控制器都返回一个单一视图模型,指定了内容(见下文),但我怎么得到它也将填充侧边栏?

public function detailsAction() 
{ 
    *some code to populate data* 

    $params = array('data' => $data);    

    $viewModel = new ViewModel($params); 
    $viewModel->setTemplate('school/school/details.phtml');  

    return $viewModel; 
} 

我有一种感觉,我在这里做一些根本性的错误。

回答

1

在一个控制器可以使用view models nesting包括“子模板”和layout plugin

public function fooAction() 
{ 
    // Sidebar content 
    $content = array(
     'name'  => 'John' 
     'lastname' => 'Doe' 
    ); 
    // Create a model for the sidebar 
    $sideBarModel = new Zend\View\Model\ViewModel($content); 
    // Set the sidebar template 
    $sideBarModel->setTemplate('my-module/my-controller/sidebar'); 

    // layout plugin returns the layout model instance 
    // First parameter must be a model instance 
    // and the second is the variable name you want to capture the content 
    $this->layout()->addChild($sideBarModel, 'sidebar'); 
    // ... 
} 

现在你只呼应的布局脚本变量:

<?php 
    // 'sidebar' here is the same passed as the second parameter to addChild() method 
    echo $this->sidebar; 
?> 
+0

感谢Josias!正是我需要的! – jonadams51 2013-03-12 16:11:36

6

您可以通过使用partial view helper

<div id="main" class="span8 listings"> 
    <?php echo $this->content; ?> 
</div> 

<div id="sidebar" class="span4"> 
    <?php echo $this->partial('sidebar.phtml', array('params' => $this->params)); ?> 
</div> 
+0

谢谢布拉姆。然而,这将工作,边栏是整个网站,但上述解决方案只有在添加到每个特定视图时才有效。 – jonadams51 2013-03-11 16:02:15

+1

'sidebar.phtml'部分在您的布局中呈现,因此它在侧面。这些参数是特定于行为的,但如果您不需要在侧边栏中执行任何特定于操作的逻辑,则不必传递该参数。 – 2013-03-11 16:10:48

0

// Module.php add it是

use Zend\View\Model\ViewModel; 


public function onBootstrap($e) 
{ 
    $app = $e->getParam('application'); 
    $app->getEventManager()->attach('dispatch', array($this, 'setLayout')); 
} 

public function setLayout($e) 
{ 
    // IF only for this module 
    $matches = $e->getRouteMatch(); 
    $controller = $matches->getParam('controller'); 
    if (false === strpos($controller, __NAMESPACE__)) { 
     // not a controller from this module 
     return; 
    } 
    // END IF 

    // Set the layout template 
    $template = $e->getViewModel(); 
    $footer = new ViewModel(array('article' => "Dranzers")); 
    $footer->setTemplate('album/album/footer'); 
    $template->addChild($footer, 'sidebar'); 
}