Smarty 作為經典 PHP 模板引擎,其核心優勢在於「業務邏輯與展示分離」。本文通過一個完整的 POST 表單提交案例,演示從配置初始化、頁面渲染、表單提交、數據處理到結果回顯的全鏈路實現。
project/
├── libs/
│ └── Smarty.class.php
├── templates/ # 模板文件目錄
│ ├── kk.html # 首頁模板
│ └── m.tpl # 結果頁模板
├── templates_c/ # 編譯緩存目錄(需寫入權限)
├── configs/ # 配置文件目錄
├── cache/ # 緩存目錄(需寫入權限)
├── conf.php # Smarty 通用配置
├── index.php # 首頁控制器
└── submit.php # 表單處理控制器
<?php
// conf.php
header("Content-Type: text/html; charset=UTF-8");
require_once '../libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = 'templates/';
$smarty->compile_dir = 'templates_c/';
$smarty->config_dir = 'configs/';
$smarty->cache_dir = 'cache/';
// $smarty->caching = true; // 生產環境可開啟緩存
?>
<?php
// index.php
require_once 'conf.php';
$smarty->assign('content', 'welcome to arrival');
$smarty->assign('mylife', [
"生活", "吃飯", "夢想", "涼風",
"報仇", "fuck someone", "fuck you die"
]);
$smarty->display('kk.html');
?>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Smarty POST 示例</title>
</head>
<body>
<h1>{$content}</h1>
<h2>生活片段</h2>
{section name=truelife loop=$mylife}
{$mylife[truelife]}<br/>
{/section}
<p>{html_select_time use_24_hours=true}</p>
<form id="form1" name="form1" method="post" action="submit.php">
<p>
<label for="conteng">標題:</label>
<input type="text" name="conteng" id="conteng" />
</p>
<p>
<label for="ct">內容:</label>
<textarea name="ct" id="ct" cols="45" rows="5"></textarea>
</p>
<input type="submit" name="submit" id="submit" value="提交" />
</form>
</body>
</html>
<?php
// submit.php
require_once 'conf.php';
// 接收 POST 數據
$content = $_POST['conteng'] ?? '';
$textarea = $_POST['ct'] ?? '';
$smarty = new Smarty();
$smarty->template_dir = 'templates/';
$smarty->compile_dir = 'templates_c/';
$smarty->config_dir = 'configs/';
$smarty->cache_dir = 'cache/';
// 賦值給模板
$smarty->assign('content', $content);
// 處理多行文本:按換行符分割為數組
$lines = explode("\r\n", $textarea);
// 兼容 Linux/Unix 換行符
if (count($lines) === 1) {
$lines = explode("\n", $textarea);
}
$smarty->assign('ml', $lines);
$smarty->display('m.tpl');
?>
<h1>{$content}</h1>
<h2>提交內容逐行顯示:</h2>
{section name=kk loop=$ml}
{$ml[kk]}<br/>
{/section}
| 語法 | 說明 | 示例 |
|---|---|---|
{$var} | 輸出變量 | {$content} |
{section name=i loop=$arr} | 遍歷數組 | 見上文 mylife/ml 遍歷 |
{$arr[i]} | 訪問數組元素 | {$mylife[truelife]} |
{html_select_time} | 內置函數:生成時間選擇框 | {html_select_time use_24_hours=true} |
htmlspecialchars() 或使用 Smarty 內置 |escape 修飾符防 XSS$_POST 鍵是否存在,提供友好默認值{extends}/{block} 實現佈局復用(需 Smarty 3+)$smarty->caching = true,設置合理 cache_lifetime| 現象 | 可能原因 | 解決方案 |
|---|---|---|
| 模板變量不顯示 | assign 變量名與模板不一致 | 檢查大小寫、拼寫;使用 {$smarty.get} 調試 |
| section 不循環 | 數組為空或非索引數組 | 確保傳入數值索引數組;使用 @count 判斷 |
| 權限錯誤 | templates_c/cache 目錄不可寫 | chmod 777 templates_c cache (Linux) |
這個完整案例展示了 Smarty 「PHP 處理邏輯、模板負責展示」的核心思想,是理解 MVC 模式在傳統 PHP 開發中落地的優秀入門實踐。