Zend Framework 2 一个布局中的两个模板? [英] Zend Framework 2 two templates in one layout?

查看:25
本文介绍了Zend Framework 2 一个布局中的两个模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

public 函数 detailsAction(){*一些填充数据的代码*$params = array('data' => $data);$viewModel = new ViewModel($params);$viewModel->setTemplate('school/school/details.phtml');返回 $viewModel;}

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

解决方案

在控制器中,您可以使用 视图模型嵌套布局插件:

公共函数 fooAction(){//侧边栏内容$content = 数组('名称' =>'约翰''姓氏' =>母鹿");//为侧边栏创建模型$sideBarModel = new Zend\View\Model\ViewModel($content);//设置侧边栏模板$sideBarModel->setTemplate('my-module/my-controller/sidebar');//布局插件返回布局模型实例//第一个参数必须是模型实例//第二个是你想要捕获内容的变量名$this->layout()->addChild($sideBarModel, 'sidebar');//...}

现在您只需在布局脚本中回显变量:

sidebar;?>

In each module in my application I'll have a main content section and a sidebar menu.

In my layout I have the following...

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

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

My controllers all return a single ViewModel which specifies the content (see below) but how do I get it to also populate the sidebar?

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

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

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

    return $viewModel;
}

I've got a feeling I am doing something fundamentally wrong here.

解决方案

In a controller you could use view models nesting and the 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');
    // ...
}

Now you just echo the variable in the layout script:

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

这篇关于Zend Framework 2 一个布局中的两个模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆