在程式設計師與美術設計師協作的專案中,FastTemplate 提供了一種輕量級的解決方案,將 PHP 邏輯與 HTML 版面完全分離。本文詳細介紹 FastTemplate 的核心概念、基本操作與進階應用。
class.FastTemplate.php),載入極快FastTemplate 基於「巨集替換」運作:
{MACRO_NAME} 標記替換點$tpl->assign('MACRO_NAME', 'value') 賦值$tpl->parse() 進行替換並輸出<?php
include 'class.FastTemplate.php3';
$tpl = new FastTemplate('.');
// 定義模板對應關係
$tpl->define(array(
'foo' => 'foo.tpl',
'bar' => 'bar.tpl'
));
?>
<?php
// 賦值給最小單元
$tpl->assign('NAME', 'me');
$tpl->assign('PAGETITLE', 'Welcome!');
// 解析子模板 foo,結果存入 PAGECONTENT
$tpl->parse('PAGECONTENT', 'foo');
// 解析主模板 bar,其中包含 {PAGECONTENT}
$tpl->parse('MAIN', 'bar');
// 輸出最終結果
$tpl->FastPrint('MAIN');
?>
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 使用正則表達式進行巨集替換,每個正則僅編譯一次。對於高流量站點,建議:
ob_start())減少 I/O 操作mod_gzip 壓縮傳輸FastTemplate 雖然不是現代 PHP 框架的主流選擇,但其極簡的設計哲學與零依賴特性,使其在輕量級專案、舊系統維護、嵌入式環境中仍具備獨特價值。