Zend Framework 入門(4)—頁面佈局

huidaoli發表於2013-07-25

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,加入下面兩行程式碼:

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

 

相關文章