下載最新版 Smarty(示例為 3.1.12),解壓後將 demo/ 與 libs/ 複製至 Web 根目錄(如 /var/www/yqting/)。重點:必須將 cache/ 和 templates_c/ 設置為可讀寫權限(chmod 777),否則編譯與緩存失效。
啟動 Apache,訪問 https://localhost/yqting/demo/index.php 即可看到演示頁面。
yqting/
├── demo/
│ ├── cache/ 緩存文件目錄
│ ├── configs/ 配置文件目錄
│ ├── index.php 入口文件
│ ├── plugins/ 自定義插件
│ ├── templates/ 模板文件目錄
│ └── templates_c/ 編譯後文件目錄
└── libs/
├── debug.tpl 調試模板
├── plugins/ 核心插件(不可修改)
│ ├── SmartyBC.class.php Smarty 2 兼容層
│ ├── Smarty.class.php 核心類
│ └── sysplugins/ 系統插件(核心功能)
擴展插件:可將自定義插件放入 libs/plugins/,或按 demo/ 結構另建 plugins/、cache/、configs/、templates/、templates_c/ 目錄(後兩者需可寫)。
weibo/ 目錄及子目錄,設置權限。index.tpl:<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
<title>Smarty</title>
</head>
<body>
username: {$Name}
</body>
</html>
index.php:<?php
require '../libs/Smarty.class.php';
$smarty = new Smarty();
$username = "Smarty";
$smarty->assign("Name", $username);
$smarty->display('index.tpl');
?>
Smarty 3 構造函數已預設 template_dir、compile_dir、config_dir、cache_dir,無需手動指定。訪問 https://localhost/yqting/weibo/index.php 輸出 username:Smarty。
| 代碼片段 | 說明 |
|---|---|
/**/ | 文件頭註釋,記錄用途、版權、作者、時間,屬良好風格 |
require_once | 引入 Smarty 核心類,路徑務必正確 |
$smarty = new Smarty() | 實例化 Smarty 對象 |
$smarty->template_dir | 指定模板目錄,默認 ./templates/,建議顯式聲明 |
$smarty->compile_dir | 指定編譯目錄,默認 ./templates_c/,Linux 下需可寫 |
$smarty->left_delimiter / right_delimiter | 定義模板變量分隔符,默認 { },常改為 {# #} 或 <!--{ }--> 避免與 JS 衝突 |
$smarty->cache_dir | 緩存目錄,默認 ./cache/,需可寫 |
$smarty->cache_lifetime | 緩存有效期(秒),-1 永不過期,0 每次重建,示例設 1 天 |
$smarty->caching = 1 | 啟用緩存:0 關閉,1 用當前 cache_lifetime,2 用緩存創建時的值 |
$smarty->assign("name", $val) | 核心賦值方法,將 PHP 變量映射到模板變量 |
$smarty->display("index.tpl") | 解析並輸出模板,文件名相對於 template_dir |
執行後 templates_c/ 與 cache/ 會自動生成編譯/緩存文件(以 %% 開頭),切勿手動修改。
$smarty->assign() 傳遞數據plugins/ 目錄存放項目專用修飾符、區塊函數,保持模板簡潔Smarty 作為成熟模板引擎,嚴格分離 PHP 與 HTML,配合 MVC 結構可顯著提升項目可維護性與團隊協作效率。