首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 模板引擎 FastTemplate 實戰指南:分離邏輯與表現層

     編輯:PHP 相關知識

在程式設計師與美術設計師協作的專案中,FastTemplate 提供了一種輕量級的解決方案,將 PHP 邏輯與 HTML 版面完全分離。本文詳細介紹 FastTemplate 的核心概念、基本操作與進階應用。

為什麼選擇 FastTemplate?

  • 秒級改版:修改模板檔即可改變整站外觀,無需動到 PHP 代碼
  • 職責分離:設計師只處理 HTML,不需理解 PHP 邏輯
  • 極致效能:核心類別僅一個檔案(class.FastTemplate.php),載入極快
  • 多國語言支援:透過參數切換模板組,輕鬆實現多語系站點
  • 模板復用:表單、列表等通用元件可跨專案復用

核心概念:巨集替換機制

FastTemplate 基於「巨集替換」運作:

  1. 模板檔中使用 {MACRO_NAME} 標記替換點
  2. PHP 端透過 $tpl->assign('MACRO_NAME', 'value') 賦值
  3. 呼叫 $tpl->parse() 進行替換並輸出

基本操作流程

1. 初始化與定義模板

<?php
include 'class.FastTemplate.php3';
$tpl = new FastTemplate('.');

// 定義模板對應關係
$tpl->define(array(
    'foo' => 'foo.tpl',
    'bar' => 'bar.tpl'
));
?>

2. 賦值與解析

<?php
// 賦值給最小單元
$tpl->assign('NAME', 'me');
$tpl->assign('PAGETITLE', 'Welcome!');

// 解析子模板 foo,結果存入 PAGECONTENT
$tpl->parse('PAGECONTENT', 'foo');

// 解析主模板 bar,其中包含 {PAGECONTENT}
$tpl->parse('MAIN', 'bar');

// 輸出最終結果
$tpl->FastPrint('MAIN');
?>

3. 模板檔案結構

bar.tpl(主模板)
<HTML>
<HEAD><TITLE>Feature world - {PAGETITLE}</TITLE></HEAD>
<BODY BGCOLOR=BLACK TEXT=WHITE>
<H1>{PAGETITLE}</H1>
{PAGECONTENT}
</BODY>
</HTML>

foo.tpl(子模板)
很明顯示什麼都沒做。請看{NAME}.

進階應用:動態建立表格

利用 parse() 的附加模式(模板名前加 .),可累加內容建立複雜結構:

<?php
// 建立表格列
$tpl->parse('TPL1', 'foo');        // 第一次解析
$tpl->parse('TPL1', '.bar');       // 附加模式:在 TPL1 後追加 bar 內容
?>

實際案例:目錄列表生成器

<?php
include 'class.FastTemplate.php3';

function InitializeTemplates() {
    global $tpl;
    $tpl = new FastTemplate('.');
    $tpl->define(array(
        'page'      => 'page.tpl',
        'table'     => 'table.tpl',
        'table_row' => 'table_row.tpl'
    ));
}

function ReadCurrentDirectory() {
    global $tpl;
    $handle = opendir('.');
    while ($filename = readdir($handle)) {
        $tpl->assign('FILENAME', $filename);
        $tpl->assign('FILESIZE', filesize($filename));
        $tpl->parse('TABLE_ROWS', '.table_row'); // 累加每一列
    }
    closedir($handle);
    $tpl->parse('PAGE_CONTENT', 'table');
}

function PrintPage($title) {
    global $tpl;
    $tpl->assign('PAGE_TITLE', $title);
    $tpl->parse('FINAL', 'page');
    $tpl->FastPrint('FINAL');
}

InitializeTemplates();
ReadCurrentDirectory();
PrintPage('Yet Another Demo');
?>

效能考量

FastTemplate 使用正則表達式進行巨集替換,每個正則僅編譯一次。對於高流量站點,建議:

  • 搭配 PHP 輸出緩衝(ob_start())減少 I/O 操作
  • 考慮 APC、Zend Cache 等 opcode 快取加速器
  • 靜態內容可搭配 mod_gzip 壓縮傳輸

FastTemplate 雖然不是現代 PHP 框架的主流選擇,但其極簡的設計哲學與零依賴特性,使其在輕量級專案、舊系統維護、嵌入式環境中仍具備獨特價值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved