模板引擎核心概念:分離邏輯與表現。最簡單的實作方式是使用預設標記(如 {title})配合 str_replace() 進行替換。本文示範最基礎的模板生成靜態頁面流程。
templates.htm<html>
<head>
<title>{title}</title>
</head>
<body>
<p>Hello {hello}</p>
</body>
</html>
<?php
// 1. 定義資料
$data = [
'title' => 'bianceng.cn',
'hello' => 'www.bianceng.cn!'
];
// 2. 讀取模板
$template = file_get_contents('templates.htm');
// 3. 批次替換
$search = array_map(function($k) { return "{".$k."}"; }, array_keys($data));
$replace = array_values($data);
$output = str_replace($search, $replace, $template);
// 4. 輸出或儲存
echo $output; // 直接輸出
// file_put_contents('output.html', $output); // 或存成靜態檔
?>
<html>
<head>
<title>bianceng.cn</title>
</head>
<body>
<p>Hello www.bianceng.cn!</p>
</body>
</html>
| 功能 | 實作方式 | 範例語法 |
|---|---|---|
| 條件判斷 | preg_replace_callback + eval (不推薦) 或自製解析器 | {if $user.logged}...{/if} |
| 迴圈輸出 | 區塊標記 + 重複替換 | {foreach $items as $item}...{/foreach} |
| 模板繼承 | 區塊替換機制 (如 Twig/Blade) | {extends 'layout.html'} |
| 快取編譯 | 將模板編譯為 PHP 程式碼快取 | 大幅提升效能 |
| 自動跳脫 | 預設 htmlspecialchars 防 XSS | {$var|escape} |
file_put_contents() 寫入 public/article/123.html