Zend Framework 1 的 `Zend_Layout` 元件實現「兩步驟視圖」模式:全域佈局(Layout)包裝各 Action 視圖。正確配置能實現頁面結構復用、區塊化管理與維護性提升。本文詳細說明從配置啟用到佈局腳本撰寫的完整流程。
檔案:application/configs/application.ini
[production]
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"
resources.layout.layout = "layout" ; 預設佈局腳本名稱(layout.phtml)
; 啟用 View 資源(Layout 依賴 View)
resources.view[] = ; 空值即可啟用 View
resources.view.doctype = "XHTML1_STRICT"
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctype()
{
$this->bootstrap('view');
$view = $this->getResource('view');
$view->doctype('XHTML1_STRICT'); // 設定文件型態
}
// 可選:自訂 Layout 實例化邏輯
protected function _initLayout()
{
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$layout->setViewSuffix('phtml'); // 視圖副檔名
}
}
application/layouts/scripts/layout.phtml<?php echo $this->doctype() ?>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ZF Application</title>
<?php echo $this->headLink()->appendStylesheet('/css/global.css') ?>
<?php echo $this->headScript()->appendFile('/js/app.js') ?>
</head>
<body>
<div id="header">
<div class="logo"><b>ZF Quickstart</b></div>
<nav>
<a href="<?php echo $this->url(['controller' => 'guestbook'], 'default', true) ?>">留言板</a>
</nav>
</div>
<div id="content">
<?php echo $this->layout()->content ?>
</div>
<div id="footer">
© 2024 My App
</div>
</body>
</html>
| 語法 | 用途 |
|---|---|
$this->layout()->content | 輸出 Action 視圖內容(核心) |
$this->layout()->varName | 存取佈局變數(控制器可 `$this->_helper->layout()->varName = $val` 設定) |
$this->placeholder('key') | 佔位符,視圖可 `$this->placeholder('key')->set('content')` 注入 |
$this->headTitle() | 管理 ` |
$this->headLink() | 管理 `` |
$this->headScript() | 管理 `
PHP 程式設計排行推薦文章
copyright © 萬盛學電腦網 all rights reserved
|