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

PHPLib 模板引擎詳解:變數替換、區塊巢狀與檔案輸出

     編輯:PHP 綜合知識

PHPLib 模板特色

  • 純 PHP 實作,效能優於早期 Perl 移植的 FastTemplate。
  • 使用 preg_replace() 解析,速度較 ereg_replace() 快。
  • 支援動態區塊巢狀(Block Nesting),FastTemplate 不支援。
  • 物件導向設計,易於擴充。

基本流程

  1. include "template.inc" 載入類別。
  2. $t = new Template("/path/to/templates/") 建立模板物件,設定根目錄。
  3. $t->set_file("handle", "template.ihtml") 關聯模板檔案與控制代碼。
  4. $t->set_var("var_name", $php_var) 設定模板變數值。
  5. $t->parse("output_handle", "template_handle") 解析替換,結果存入 output_handle。
  6. $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():清空所有已設定變數與檔案關聯。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved