將 caching 設為 true,指定 cache_dir。使用 cache_lifetime 設定快取存活秒數。若同一頁面需多組快取,於 display 或 fetch 傳入第二參數 cache_id:
$smarty->display('index.tpl', $my_cache_id);
可針對不同 $_GET 產生不同快取。
clear_all_cache(); // 清除所有
clear_cache('index.tpl'); // 清除特定模板
clear_cache('index.tpl', $cache_id); // 清除指定 ID
設定 cache_handler_func 使用自訂函式處理快取:
$smarty->cache_handler_func = "myCache";
function myCache($action, &$smarty_obj, &$cache_content, $tpl_file=null, $cache_id=null, $compile_id=null) {
switch($action) {
case "read": // 讀取快取內容
case "write": // 寫入快取
case "clear": // 清空快取
}
}
建議以 md5($tpl_file.$cache_id.$compile_id) 作為唯一快取 ID,可搭配 gzcompress/gzuncompress 壓縮。
使用 {insert} 或 register_block 讓特定區塊不被快取。
// 區塊外掛範例:block.cacheless.php
function smarty_block_cacheless($param, $content, &$smarty) { return $content; }
模板中使用:{cacheless} 未快取內容 {/cacheless}。
<?php
include('Smarty.class.php');
$smarty = new Smarty;
$smarty->caching = true;
$smarty->cache_lifetime = 6;
$smarty->display('cache.tpl');
?>
// cache.tpl
已經快取的: {$smarty.now}<br>
{cacheless}
沒有快取的: {$smarty.now}
{/cacheless}
透過區塊外掛靈活控制快取範圍,提升效能同時保持動態內容即時性。