首頁 > ZEND framework, 網頁設計 > ZF in ∞ days –> day 4 –> 使用 Layout 來排版

ZF in ∞ days –> day 4 –> 使用 Layout 來排版

2010年5月30日  瀏覽次數 : 3,505

ZF 提供了一隻叫做 LAYOUT 的 API,其實他與 VIEW 是很像的,主要是協助我們來做網站的整體架構排版,如果是開發一個較完整的案子,一定都會遇到某些區塊是重複使用的,例如 header , footer 或是 menu , sidebar 等等的,因此 Layout 可以協助我們更容易建立起版面。

image Bloggerspot 的網頁也可以利用 Layout 來排版

當在用 CI 時,我們會在 Controller 產生 View 時,同時匯入 header , menu , sidebar , content , footer 這些不同的 VIEW,不過經常會造成每一個 ACTION 都要重複匯入,因此當使用 ZF 的 Layout 就可以更快的完成每一隻程式的共同版面。

STEP 1 :

如 day1 ,建立一個 ZF 專案命名為 day4 ,並且開啟 application/configs/application.ini 檔案

並且在 [production] 區段加入以下兩行

resources.layout.layoutPath = APPLICATION_PATH "/views/layouts/"
resources.layout.layout = "layout"

 

image

STEP 2 :

在 views 資料夾 在建立一個資料夾 layouts 並在建立一個 ZF view ,命名為 layout.phtml

並輸入以下內容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php echo $this->doctype(); ?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php echo $this->headMeta(); ?>
<?php echo $this->headTitle(); ?>
</head>
 
<body>
<div class="header">Welecome <h1><?php echo $this->escape($this->title); ?></h1></div>
<div class="content">
 
  <?php echo $this->layout()->content; ?>
 
</div>
<div class="footer"> copyright corAusir</div>
</body>
</html>

image

STEP 3 :

接著我們在瀏覽器打開 http://localhost/day4/public/index.php

便可以看到我們剛剛設定的 header , footer 已經可以正確顯示

image

STEP 4 :

不過這樣並不能了解 LAYOUT 對於每一個 ACTION 套用的感覺

因此我們打開 IndexController.php

並將 CODE 修改如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php
 
class IndexController extends Zend_Controller_Action {
 
	public function init() {
		/* Initialize action controller here */
		//如果原本的 INIT 有動作先重新執行
		parent::init ();
		//取得 LAYOUT 物件
		$layout = $this->_helper->layout ();
		//取得 VIEW 物件
		$view = $layout->getView ();
		//設定 LAYOUT 的編碼
		$view->headMeta ()->appendHttpEquiv ( 'Content-Type', 'text/html;charset=utf-8' );
		$view->headTitle ()->setSeparator ( ' - ' );
		//設定 LAYOUT 網頁標題
		$view->headTitle ( "Layout 測試" );
	}
	public function indexAction() {
		// action body
	}
	public function a1Action(){
		//指定變數內容
		$this->view->title = "A1 測試";
		$this->view->text = "A1 內容";
	}
	public function a2Action(){
		//指定變數內容
		$this->view->title = "A2 測試";
		$this->view->text = "A2 內容";
	}
}

image

STEP 5 :

接著我們將各兩個 Action 也建立各自的 View ,其CODE 都只需要填入一行 a1.phtml 與 a2.phtml

1
<?php echo $this->escape($this->text); ?>

image

STEP 6 :

接著我們在瀏覽器各自打開 a1 與 a2 兩個 action

http://localhost/day4/public/index.php/index/a1

image

http://localhost/day4/public/index.php/index/a2

image

如何,我們成功的兩個網頁都套上相同的 header , footer ,但是卻不會改變 view 的檔案。

如果該頁面使用不同的 LAYOUT 或是要關掉 也可以利用 disableLayout 或是 setLayout 來處理。

不過俗話說師傅帶進門,修行靠個人,還是趕快去翻 ZF DOC 吧。

Random Posts

Loading…

:: 把這篇好文推到書籤網站與更多人分享吧 ::
  • funp
  • Hemidemi
  • YahooKimo
  • Google
  • udn
  • Haohao
  • Live

相關文章 :

Ausir ZEND framework, 網頁設計 , , , , , ,

  1. 2011年8月20日02:49 | #1

    hi lose you fat today..sucess formula!!!

  1. 本篇文章目前尚無任何 trackbacks 和 pingbacks。