Zend Framework 2在一个布局中有两个模板?

时间:2013-03-11 15:24:16

标签: zend-framework2

在我的应用程序的每个模块中,我将有一个主要内容部分和侧边栏菜单。

在我的布局中,我有以下内容......

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

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

我的控制器都返回一个ViewModel,它指定了内容(见下文)但是如何让它也填充侧边栏?

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

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

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

    return $viewModel;
}

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

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

在控制器中,您可以使用view models nestinglayout 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;
?>

答案 2 :(得分:0)

// Module.php添加它是

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');
}