Zend Framework 的頁面配置模組——Zend_Layout——既可以跟 MVC 一起使用,也可以單獨使用。本文只討論與 MVC 一起使用的情況。
1、布局指令碼
在 application/views 下建立一個 layouts 的檔案夾。主布局指令碼 layout.phtml 代碼如下:
<?php echo $this->doctype('XHTML1_STRICT') ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php echo $this->headTitle() ?>
<?php
$this->headLink()->appendStylesheet("/styles/main.css");
// add more links ...
?>
<?php echo $this->headLink() ?>
</head>
<body>
<div id="header">
<?php echo $this->partial('header.phtml') ?>
</div>
<table>
<tr>
<td valign=top>
<div id="leftcolumn">
<?php echo $this->partial('leftcolumn.phtml') ?>
</div>
</td>
<td valign=top>
<div id="content">
<?php echo $this->layout()->content ?>
</div>
</td>
</tr>
</table>
<div id="footer">
<?php echo $this->partial('footer.phtml') ?>
</div>
</body>
</html> |
除了 layout.phtml 之外,還需要編寫 header.phtml,leftcolumn.phtml,footer.phtml,以及 main.css 等檔案。
Zend Framework 的文檔中用一個視圖表示了頁面配置的應用。
2、設定頁面配置
在 MVC 下設定頁面配置非常簡單,編輯 html/index.php,加入下面兩行代碼:
/** Setup layout */
require_once 'Zend/Layout.php';
Zend_Layout::startMvc($rootPath . '/application/views/layouts'); |
注意:在啟動頁面配置後,要調整已有的各個頁面,把不需要的 html 元素,如<header> <title> <body> 等去掉。另外,可以通過 $this->headTitle() 來設定頁面的題頭。
改變頁面的布局也很簡單,只需在控制器中用下面的代碼即可:
$this->_helper->layout->setLayout('new_layout');
如果一個控制器所有動作都使用同一個頁面配置,可以通過控制器的初始化函數來設定:
public function init() {
parent::init();
$this->_helper->layout->setLayout('new_layout');
}