模板文件包含佔位符標簽 (如 {title}、{content}),PHP 讀取模板內容,**字符串替換**佔位符為動態數據,寫入目標 HTML 文件。這是最原始、最高效、無依賴的「模板引擎」雛形。
$value) {
$html = str_replace('{' . $key . '}', $value, $html);
}
// 確保輸出目錄存在
$dir = dirname(OUT_DIR . $outputFile);
if (!is_dir($dir)) mkdir($dir, 0755, true);
return (bool)file_put_contents(OUT_DIR . $outputFile, $html, LOCK_EX);
}
// 使用
$data = [
'site_title' => '我的部落格',
'site_url' => 'https://example.com',
'content' => '這是文章內容... ',
];
render('article.tpl', $data, 'article-123.html');
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>{site_title} - 我的站點</title>
</head>
<body>
<header><h1>{site_title}</h1></header>
<main>{content}</main>
<footer>© {site_url}</footer>
</body>
</html>
function renderAdvanced(string $tpl, array $data): string {
$html = file_get_contents($tpl);
// 1. 簡單條件 {if condition}...{/if} (僅演示,生產請用成熟引擎)
$html = preg_replace_callback('/\{if\s+(.+?)\}(.+?)\{\/if\}/s', function($m) use ($data) {
// 極其危險:eval 代碼注入風險!僅教學演示
// 實際應用請用 Symfony ExpressionLanguage 或自定義解析器
$cond = @eval("return (bool)($m[1]);");
return $cond ? $m[2] : '';
}, $html);
// 2. 循環 {foreach $items as $item}...{/foreach}
$html = preg_replace_callback('/\{foreach\s+\$(\w+)\s+as\s+\$(\w+)\}(.+?)\{\/foreach\}/s', function($m) use ($data) {
$arr = $data[$m[1]] ?? [];
$out = '';
foreach ($arr as $item) {
$scope = $data + [$m[2] => $item];
$out .= renderAdvanced($m[3], $scope); // 遞歸處理嵌套
}
return $out;
}, $html);
// 3. 變量替換 (最後統一替換)
foreach ($data as $k => $v) {
if (is_scalar($v) || is_null($v)) {
$html = str_replace('{' . $k . '}', (string)$v, $html);
}
}
return $html;
}
htmlspecialchars($v, ENT_QUOTES, 'UTF-8'),除非明確標記為安全 HTML。../../etc/passwd。| 引擎 | 特點 | 適用場景 |
|---|---|---|
| Twig | Symfony 標準、沙箱安全、繼承塊、編譯緩存、擴展豐富 | 現代 PHP 專案首選 |
| Blade (Laravel) | 語法糖豐富、指令系統、編譯緩存、無沙箱但生態強 | Laravel 專案 |
| Smarty 3 | 編譯型、模板繼承、插件機制、緩存、安全策略 | 傳統 MVC、團隊協作 |
| Plates | 原生 PHP 模板、無編譯、零依賴、繼承、佈局 | 不想學新語法、輕量 |
| Latte | 上下文感知自動轉義、類型系統、PHP 8+ 原生、極快 | 安全優先、現代專案 |
「標簽替換生成靜態頁」是理解模板引擎本質的最佳切入點。**生產環境請直接使用成熟引擎 (Twig/Blade/Latte)**,享受沙箱安全、繼承佈局、編譯緩存、擴展生態等紅利。自研僅適合極簡場景或教學演示。