{$article.title}
{$article.content}
Smarty 是 PHP 模板引擎,實現業務邏輯與表現層分離。程序員專注 PHP 代碼,美工專注 HTML/CSS,團隊協作效率大幅提升。
{block}/{extends} 實現佈局復用,類似 Django/Jinja2。Smarty-3.1.12/ ├── libs/ │ ├── Smarty.class.php # 核心類 │ ├── sysplugins/ # 內建插件 │ └── plugins/ # 自定義插件目錄 ├── demo/ # 示例項目(可重命名為項目名) │ ├── cache/ # 緩存文件(需寫入權限) │ ├── configs/ # 配置文件 │ ├── templates/ # 模板文件 (.tpl) │ └── templates_c/ # 編譯文件(需寫入權限)
setTemplateDir('demo/templates/');
$smarty->setCompileDir('demo/templates_c/');
$smarty->setCacheDir('demo/cache/');
$smarty->setConfigDir('demo/configs/');
// 開發階段:強制編譯、關閉緩存
$smarty->setForceCompile(true);
$smarty->setCaching(false);
// 上線階段:關閉強制編譯、開啟緩存
// $smarty->setForceCompile(false);
// $smarty->setCaching(true);
// $smarty->setCacheLifetime(3600); // 緩存 1 小時
// 分界符(默認 {},可改避開與 JS/CSS 衝突)
$smarty->left_delimiter = '{';
$smarty->right_delimiter = '}';
// 調試模式
// $smarty->setDebugging(true);
$smarty->assign('name', '張三');
$smarty->assign('users', [
['id' => 1, 'name' => '李四'],
['id' => 2, 'name' => '王五'],
]);
$smarty->assign('config', ['site_name' => 'MySite', 'version' => '1.0']);
{* 模板註釋,不會輸出到 HTML *}
{$config.site_name} - 歡迎
你好,{$name}!
{if $users}
暫無用戶數據
{/if} {* 包含子模板 *} {include file="footer.tpl"}$smarty->display('index.tpl');
| 語法 | 說明 | 示例 |
|---|---|---|
| 變量輸出 | 直接輸出變量值 | {$name} {$user.name} {$arr.0} |
| 條件判斷 | if/elseif/else | {if $a gt 10}...{elseif $a eq 5}...{else}...{/if} |
| 循環 | foreach/section | {foreach $arr as $v} {section name=sec loop=$arr} |
| 包含模板 | 復用片段 | {include file="header.tpl" title="首頁"} |
| 字面量 | 禁用解析,輸出原文(JS/CSS 必備) | {literal}{/literal} |
| 捕獲輸出 | 將區塊輸出存入變量 | {capture name=block}...{/capture}{$smarty.capture.block} |
| 配置文件 | 載入 .conf 鍵值對 | {config_load file="lang.conf" section="zh"} {#key#} |
| 模板繼承 | 佈局復用 | 見下文「模板繼承」 |
| 獲取遠程內容 | fetch URL | {fetch file="https://api.example.com/data" assign=data} |
{block name=title}默認標題{/block} {block name=header}網站 Header{/block} {block name=content}主內容區{/block}
{extends file="layout.tpl"}
{block name=title}文章頁 - {$article.title}{/block}
{block name=content}
{$article.title}
{$article.content}
{/block}
{* 未定義的 block (如 footer) 將繼承父模板內容 *}
{extends} 開頭。{block} 會覆蓋父模板同名區塊。// 開啟緩存
$smarty->setCaching(true);
$smarty->setCacheLifetime(3600); // 秒
// 模板中局部不緩存(如用戶個人信息)
{nocache}
歡迎,{$user.name}!餘額:{$user.balance}
{/nocache}
config/smarty.conf.php,各項目 require 後實例化 $smarty,統一目錄路徑。date_format、truncate)放入 plugins/,命名規則 modifier.名稱.php,函數名 smarty_modifier_名稱。Deny from all 禁止直接訪問 .tpl。Smarty 3 提供編譯緩存、模板繼承、插件擴展等現代模板引擎特性,學習曲線平緩,適合中大型 PHP 專案。關鍵配置:開發環境強制編譯+關閉緩存,生產環境關閉強制編譯+開啟緩存+合理設置生命週期。