萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Smarty 模板引擎捕獲輸出內容的兩種方法:ob_start vs capture 標籤

場景

在 Smarty 模板中,需要將 {include} 或 {$smarty->display()} 的輸出捕獲為字符串變量,用於:局部靜態化、郵件模板渲染、API 返回 HTML 片段、多次復用渲染結果等。

方法一:PHP 原生 ob_start (通用、不依賴 Smarty 語法)

<?php
ob_start();
$smarty->display('StockNews/getLeft.tpl');
$html = ob_get_contents();
ob_end_clean();
// $html 現在包含模板輸出的完整 HTML 字符串
?>

優點:通用性強、無需修改模板、可捕獲任意 PHP 輸出。
缺點:嵌套 ob_start 需注意層級管理、略顯底層。

方法二:Smarty 內建 {capture} 標籤 (模板層面、語義化)

模板中使用

{* needStatic.tpl *}
{capture name=static_block}
    {section name=i loop=$items}
        <div class="item">{$items[i]}</div>
    {/section}
{/capture}

{* 後續在模板中直接使用 *}
{$smarty.capture.static_block}

PHP 中獲取捕獲內容

<?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');
?>

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>

partials/home_static.tpl

{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+) 直接賦給模板變量。
  • 靜態化策略:緩存過期時間、緩存鍵設計 (URL+參數+用戶角色)、緩存清除機制 (發布新內容、後台手動清除)。
  • 大塊 HTML 字符串在 PHP 變量中傳遞可能佔用大量內存,極大頁面考慮分片輸出或直接 $smarty->display() 分段發送。

結語

掌握 ob_start 和 {capture} 兩種捕獲機制,能靈活實現局部緩存、模板復用、異步渲染等高級模板技巧。現代項目中,配合模板繼承、塊覆蓋、Edge Side Includes (ESI)、Varnish/Nginx fastcgi_cache 等邊緣緩存方案,構建多層次高性能渲染體系。

copyright © 萬盛學電腦網 all rights reserved