Smarty 是 PHP 模板引擎,**編譯型**:模板文件 (.tpl) 首次訪問編譯為 PHP 腳本存放於 templates_c/,後續直接執行編譯文件,性能接近原生 PHP。核心優勢:**業務邏輯與展示分離**,程序員負責 PHP,美工負責模板,協作高效。
| 適用 | 不適用 |
|---|---|
| 中大型團隊協作項目 | 極簡單項目(一人全棧) |
| 需頻繁改版、多主題皮膚 | 高實時性數據(股票行情、WebSocket 推送) |
| 模板繼承、區塊覆蓋需求強 | 追求極致性能、無緩存需求 |
project/
├── libs/
│ ├── Smarty.class.php # 核心類
│ ├── sysplugins/ # 內部插件 (不建議修改)
│ └── plugins/ # 自定義插件 (modifier, function, block)
├── templates/ # 模板文件 (.tpl)
├── templates_c/ # 編譯緩存 (需寫入權限)
├── cache/ // 靜態緩存 (需寫入權限)
└── configs/ // 配置文件 (.conf)
require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('templates/');
$smarty->setCompileDir('templates_c/');
$smarty->setCacheDir('cache/');
$smarty->setConfigDir('configs/');
// 開發環境:強制編譯、關閉緩存
$smarty->force_compile = true;
$smarty->caching = false;
// 生產環境:關閉強制編譯、開啟緩存
// $smarty->force_compile = false;
// $smarty->caching = true;
// $smarty->cache_lifetime = 3600;
// 分界符修改 (避免與 JS/Vue/React {{ }} 衝突)
$smarty->left_delimiter = '{';
$smarty->right_delimiter = '}';
// 分配變量
$smarty->assign('name', '張三');
$smarty->assign('users', [
['name' => '李四', 'age' => 25],
['name' => '王五', 'age' => 30],
]);
// 顯示模板
$smarty->display('index.tpl');
{$name} // 簡單變量
{$user.name|escape} // 修飾器:HTML 轉義
{$user.name|default:'游客'} // 默認值
{$arr.0} / {$arr.key} // 數組/對象訪問
{if $user.logged}
歡迎 {$user.name}
{elseif $user.banned}
賬號已封禁
{else}
登入
{/if}
{foreach $users as $u}
{$u.name} ({$u.age})
{foreachelse}
暫無用戶
{/foreach}
{section name=i start=0 loop=10 step=2}
{$smarty.section.i.index}
{/section}
{* layout.tpl *}
{block name=title}默認標題{/block}
{block name=content}默認內容{/block}
{block name=footer}© 2024{/block}
{* page.tpl *}
{extends file="layout.tpl"}
{block name=title}文章頁 - {$title}{/block}
{block name=content}
{$content}
{/block}
{* 整頁緩存 *}
{$smarty->caching = true;}
{* 局部不緩存 *}
{nocache}
{$user.name} {* 每次動態獲取 *}
{/nocache}
{* 模板內指定緩存時間 *}
{cache lifetime=300} ... {/cache}
在 plugins/ 下建立 modifier.truncate.php:
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $breakWords = false) {
if (mb_strlen($string) <= $length) return $string;
return mb_substr($string, 0, $length) . $etc;
}
模板中使用:{$longText|truncate:50:'...'}
$smarty->addTemplateDir(['frontend' => 'templates/frontend/', 'admin' => 'templates/admin/']),模板引用 frontend:index.tpl。$smarty->registerPlugin('function', 'url', 'my_url_func'),模板中 {url route='user' id=1}。$smarty->security_policy = new Smarty_Security($smarty); 限制 PHP 標簽、文件包含、目錄遍歷。|escape 或啟用 $smarty->escape_html = true (Smarty 3.1+)。templates_c/ cache/ 或設置 force_compile = true。{{ }} 時,修改 Smarty 分界符為 { } 或 {% %}。Smarty 以編譯緩存、模板繼承、插件機制、安全策略見長,是 PHP 傳統 MVC 專案的優秀選型。現代項目亦可配合前端框架(Vue/React)採用「後端渲染首屏 + 前端接管」混合模式,Smarty 負責首屏 SEO 與初始狀態輸出。