preg_replace() 解析,速度較 ereg_replace() 快。include "template.inc" 載入類別。$t = new Template("/path/to/templates/") 建立模板物件,設定根目錄。$t->set_file("handle", "template.ihtml") 關聯模板檔案與控制代碼。$t->set_var("var_name", $php_var) 設定模板變數值。$t->parse("output_handle", "template_handle") 解析替換,結果存入 output_handle。$t->p("output_handle") 輸出結果;或 $t->get("output_handle") 取回字串。<?php
include "template.inc";
$my_color = "blue";
$t = new Template("/home/mydir/mytemplates/");
$t->set_file("MyFileHandle", "MyTemplate.ihtml");
$t->set_var("some_color", $my_color);
$t->parse("MyOutput", "MyFileHandle");
$t->p("MyOutput");
?>
模板檔 MyTemplate.ihtml 內容:
恭喜!你贏了一輛{some_color}Honda Prelude!
輸出:恭喜!你贏了一輛藍色 Honda Prelude!
模板中以註解標記區塊:
<table>
<!-- BEGIN rowlist -->
<tr>
<!-- BEGIN collist -->
<td>{cell_value}</td>
<!-- END collist -->
</tr>
<!-- END rowlist -->
</table>
PHP 端:
$t->set_block("MyFileHandle", "rowlist", "RL");
$t->set_block("RL", "collist", "CL");
foreach ($rows as $row) {
foreach ($row['cells'] as $cell) {
$t->set_var("cell_value", $cell);
$t->parse("CL", "collist", true); // true = append
}
$t->parse("RL", "rowlist", true);
}
$t->parse("MyOutput", "MyFileHandle");
set_unknowns("remove|comment|keep"):處理未定義變數(預設 remove)。savetofile($path, $handle):將解析結果存檔(靜態化)。renew():清空所有已設定變數與檔案關聯。