在 Smarty 模板中,需要將 {include} 或 {$smarty->display()} 的輸出捕獲為字符串變量,用於:局部靜態化、郵件模板渲染、API 返回 HTML 片段、多次復用渲染結果等。
<?php
ob_start();
$smarty->display('StockNews/getLeft.tpl');
$html = ob_get_contents();
ob_end_clean();
// $html 現在包含模板輸出的完整 HTML 字符串
?>
優點:通用性強、無需修改模板、可捕獲任意 PHP 輸出。
缺點:嵌套 ob_start 需注意層級管理、略顯底層。
{* needStatic.tpl *}
{capture name=static_block}
{section name=i loop=$items}
<div class="item">{$items[i]}</div>
{/section}
{/capture}
{* 後續在模板中直接使用 *}
{$smarty.capture.static_block}
<?php
$smarty->display('needStatic.tpl'); // 執行模板,內部 capture 會存儲
$html = $smarty->_smarty_vars['capture']['static_block']; // 直接讀取內部變量
// 注意:_smarty_vars 為受保護屬性,官方建議使用 getTemplateVars() 或 fetch()
// 更規範方式:
$html = $smarty->getTemplateVars('smarty.capture.static_block'); // Smarty 3.1+
// 或直接 fetch 模板 (內部自動處理 capture)
$html = $smarty->fetch('needStatic.tpl');
<?php
// index.php
$smarty = new Smarty();
// ... 配置 ...
$staticFile = 'static/home_static.html';
if (file_exists($staticFile) && (time() - filemtime($staticFile) < 3600)) {
// 1. 靜態文件存在且未過期:直接包含靜態內容
$staticHtml = file_get_contents($staticFile);
$smarty->assign('staticContent', $staticHtml);
} else {
// 2. 生成靜態內容
ob_start();
$smarty->assign('newsList', getLatestNews(10)); // 動態數據
$smarty->display('partials/home_static.tpl'); // 包含 {capture name=static}...{/capture}
$staticHtml = ob_get_contents();
ob_end_clean();
// 寫入靜態文件 (原子寫入)
$tmp = $staticFile . '.tmp';
file_put_contents($tmp, $staticHtml);
rename($tmp, $staticFile);
$smarty->assign('staticContent', $staticHtml);
}
// 3. 動態部分 (如用戶個性化推薦、實時數據)
$smarty->assign('dynamicContent', getPersonalizedAds($userId));
// 4. 輸出主頁 (包含靜態佔位符 {$staticContent} 和動態部分)
$smarty->display('index.tpl');
?>
<!DOCTYPE html>
<html>
<head><title>首頁</title></head>
<body>
<header>...</header>
<main>
<section class="static-part">
{$staticContent|default:'加載中...'} {* 靜態化部分 *}
</section>
<section class="dynamic-part">
{$dynamicContent} {* 每次請求動態生成 *}
</section>
</main>
</body>
</html>
{capture name=static}
<div class="news-list">
{foreach $newsList as $news}
<article>
<h3><a href="/news/{$news.id}">{$news.title}</a></h3>
<p>{$news.summary}</p>
</article>
{/foreach}
</div>
{/capture}
{* 此處不直接輸出,由 PHP 通過 ob_get_contents 或 $smarty->fetch 獲取 *}
| 特性 | ob_start() | {capture} |
|---|---|---|
| 層級 | PHP 執行層 | 模板編譯層 (編譯為 ob_start) |
| 作用域 | 任意 PHP 輸出 | 僅模板輸出 |
| 嵌套支持 | 需手動管理層級 | 支持嵌套 capture (不同 name) |
| 讀取方式 | ob_get_contents() | $smarty.capture.name / $smarty->fetch() |
| 性能 | 略快 (無模板編譯開銷) | 編譯後同等 |
$smarty->_smarty_vars 為內部屬性,版本間可能變動,優先使用 fetch() 或 getTemplateVars()。{capture} 內容默認不輸出,需顯式 {$smarty.capture.name} 或 {capture name=foo assign=var} (Smarty 3+) 直接賦給模板變量。$smarty->display() 分段發送。掌握 ob_start 和 {capture} 兩種捕獲機制,能靈活實現局部緩存、模板復用、異步渲染等高級模板技巧。現代項目中,配合模板繼承、塊覆蓋、Edge Side Includes (ESI)、Varnish/Nginx fastcgi_cache 等邊緣緩存方案,構建多層次高性能渲染體系。