就本人來說,不怎麼喜歡Zend Framework,贊Symphony。Zend Framework2也出來一段時間了,有時間研究下。今天有人問了我,看了下Zend_Layout使用部分。一個基本的web頁面,可能頁面的頭和尾或某些模塊都是一樣,可以把公共的部分做成模版。不僅可以提高開發效率,也爲後期的維護帶來方便。還可以輕鬆實現切換主題機制。
第一步:在application.ini中配置layout路徑,[production]下加入:
resources.layout.layoutPath = APPLICATION_PATH "/views/scripts/layouts"
resources.layout.layout = "layout"
文件結構如下:
第二步:建立相關文件
layout.phtml文件:
<!--www.phpddt.com-->
<?php echo $this->render('header.phtml');?>
<!--來一個佈局變量-->
<?php echo $this->layout()->nav ?>
<!--默認的,$content 變量被應用程序的視圖腳本呈現內容填充。-->
<?php echo $this->layout()->content;?>
<?php echo $this->render('footer.phtml');?>
header.phtml文件:
<html>
<head>
<title>這是www.phpddt.com</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
nav.phtml文件:
<div id="nav" style="margin:20px 0;background-color: red;">
這是導航
</div>
footer.phtml文件:
<div id="footer" style="background-color: #EEEEEE; height: 30px;">
這是footer
</div>
</body>
</html>
第三步:在動作控制器中:
<?php
//@blog<http://www.phpddt.com>
require_once APPLICATION_PATH.'/models/Article.php';
require_once 'BaseController.php';
require_once 'Zend/Layout.php';
class IndexController extends BaseController
{
public function init()
{
parent::init();
//set layout
$layout = new Zend_Layout();
$layout->nav = $this->view->render('layouts/nav.phtml');
$layout->setLayout('layout');
}
//這裏的內容到$this->layout()->content中
public function indexAction()
{
$a = new Article();
$res = $a->fetchAll()->toArray();
$this->view->res = $res;
$this->render('index');
}
}
通過訪問,你可以看到,zend已經爲你加載了全部內容:
轉載來源:http://www.phpddt.com/mvc/zend_layout.html