如何在整体布局中嵌入个局部布局?
玩zend framework有一年半了,经常没事时去解析它的原代码,也因此对MVC模式的设计实现有了更深了解,同时在技术应用上也产生了些想法。之前觉认为Zend framework在布局应用上只能使用个布局模板,但在经过对代码的分析,找到了一个可以使用整体布局中嵌套一个局部布局。
如上图所示,对于整体布局即导航栏,它是所有模块中视图都要出现在,左侧的“产品分类”和“最新产品”希望它能够在点击它们下面的链接时下面右侧对应相应ACTION的视图能够正常出面,这样我们在保用整体布局的同时也用到了局部的布局。
实现代码如下:
下面为对应controller的文件代码:
class Product_IndexController extends Zend_Controller_Action
{
public $product_layout;
public function init()
{
$product_layout = new Zend_Layout();//局部布局的Zend_Layout
$product_layout->setLayoutPath(APPLICATION_PATH.'/modules/product/layouts/scripts/');//设置局部布局的脚本的位置 $product_layout->setLayout('index'); //局部布局模板文件名
$this->product_layout = $product_layout;
$product_category = new Application_Model_ProductCategoryModel();
$product = new Application_Model_ProductModel();
$this->view->product_category = $product_category;
$this->view->product = $product;
}
public function indexAction ()
{
$this->view->test = 123;
}
public function showAction()
{
$this->view->test = 'show';
}
public function postDispatch()
{
$controller = $this->_request->getControllerName();
$action = $this->_request->getActionName();
$content = array('content'=>$this->view->render('/'.$controller.'/'.$action.'.phtml'));
$this->product_layout->assign($content);
$this->_response->setBody($this->product_layout->render());
$viewRenderer = Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer');
$viewRenderer->setNoRender(true);
}
}
下面对应布局脚本:
<div class="content-left">
<div class="product-category">
<div class="product-category-header">产品分类</div>
<div>
<ul class="product-category-list">
<?php
$this->product_category->reset();
if (!$this->product_category->isEmpty()){
do {
echo '<li><a href="#">'.$this->product_category.'(?)</a></li>';
}while ($this->product_category->next());
}
?>
</ul>
</div>
</div>
<div class="product-new">
<div class="product-new-header">最新产品</div>
<div>
<ul class="product-new-list">
<?php
$this->product->loadNewProductsData();
if (!$this->product->isEmpty()){
do {
echo '<li><a href="'.$this->url(array('module'=>'product','controler'=>'index','action'=>'show'),null,true).'">'.$this->product->product_name.'</a></li>';
}while ($this->product->next());
}
?>
</ul>
</div>
</div>
</div>
<div class="content-right">
<?=$this->layout()->content ?>
</div>
下面为对应的action视图脚本
<?php
echo $this->test;
以上代码能够实现整体布局里嵌入局部布局。
好困呀!望高手指教。