| 方法 | 語法 | 適用場景 | 緩存控制力 |
|---|---|---|---|
{insert} | {insert name="getTime"} | 簡單動態片段 (時間、隨機數、用戶名) | 僅不緩存,不可配置 |
register_function | {current_time} | 自定義函數標簽,需邏輯復用 | 可控制是否緩存 (第3參數) |
register_block | {dynamic}...{/dynamic} | 大塊模板區塊動態化 | 可控制是否緩存 |
{* template/index.tpl *}
<div class="header">
當前時間:{insert name="getCurrentTime"}
</div>
<?php
// PHP 入口
function insert_getCurrentTime(array $params, Smarty $smarty): string
{
return date('Y-m-d H:i:s');
}
$smarty = new Smarty();
$smarty->caching = true;
$smarty->display('index.tpl');
特點:函數命名規則 insert_名稱,自動識別,無需註冊。參數 $params 來自模板屬性 {insert name="foo" bar="baz"} → $params['bar']。
{* template/index.tpl *}
<div>{current_time}</div>
<?php
function smarty_function_current_time(array $params, Smarty $smarty): string
{
return date('Y-m-d H:i:s');
}
$smarty = new Smarty();
$smarty->caching = true;
// 第3參數 false = 不緩存此函數輸出
$smarty->registerPlugin('function', 'current_time', 'smarty_function_current_time', false);
$smarty->display('index.tpl');
關鍵:必須在 is_cached() 判斷前註冊,否則緩存文件生成時找不到插件報錯。
{* template/index.tpl *}
<div>
頁面生成:{"0"|date_format:"%H:%M:%S"}
{dynamic}
實時時間:{"0"|date_format:"%H:%M:%S"}
{* 這裡可以放任意複雜邏輯 *}
{/dynamic}
</div>
<?php
function smarty_block_dynamic(array $params, string $content, Smarty $smarty): string
{
// $content 為區塊內已編譯的 PHP 代碼字符串
// 直接返回即可讓區塊每次重新執行
return $content;
}
$smarty = new Smarty();
$smarty->caching = true;
$smarty->registerPlugin('block', 'dynamic', 'smarty_block_dynamic', false);
$smarty->display('index.tpl');
$smarty->caching = true; // 全局開啟
$smarty->cache_lifetime = 300; // 全局壽命 5 分鐘
$smarty->caching = Smarty::CACHING_LIFETIME_CURRENT; // 僅當前請求有效 (調試用)
$smarty->compile_check = true; // 檢測模板修改自動重編譯
$smarty->force_compile = false; // 強制重編譯 (開發用)
// 模板內覆蓋
{if $user.logged}{nocache}{/if} {* 模板內局部禁用緩存 *}
{cache lifetime=600}...{/cache} {* 模板內局部設定壽命 *}
<?php
// plugins/function.date_now.php
function smarty_function_date_now(array $params, Smarty $smarty): string
{
$format = $params['format'] ?? '%b %e, %Y';
return strftime($format, time());
}
// 註冊 (可選,放入 plugins 目錄自動載入)
$smarty->registerPlugin('function', 'date_now', 'smarty_function_date_now');
// 模板使用
{date_now}
{date_now format="%Y/%m/%d"}
is_cached() 前註冊{insert} 內容不計入緩存鑰匙,若依賴用戶狀態需手動區分register_block 回調的 $content 是編譯後 PHP 代碼,非渲染結果Smarty 緩存三板斧:{insert} 輕量、register_function 復用、register_block 區塊。核心原理:編譯期靜態化,運行期動態插入。合理使用可讓 90% 頁面緩存、10% 動態完美共存。