萬盛學電腦網

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

PHP 模板引擎 Smarty 3 詳細介紹:原理、目錄結構、配置與實戰

什麼是 Smarty?

Smarty 是 PHP 模板引擎,**編譯型**:模板文件 (.tpl) 首次訪問編譯為 PHP 腳本存放於 templates_c/,後續直接執行編譯文件,性能接近原生 PHP。核心優勢:**業務邏輯與展示分離**,程序員負責 PHP,美工負責模板,協作高效。

適用與不適用場景

適用不適用
中大型團隊協作項目極簡單項目(一人全棧)
需頻繁改版、多主題皮膚高實時性數據(股票行情、WebSocket 推送)
模板繼承、區塊覆蓋需求強追求極致性能、無緩存需求

目錄結構 (Smarty 3.1+)

project/
├── libs/
│   ├── Smarty.class.php          # 核心類
│   ├── sysplugins/               # 內部插件 (不建議修改)
│   └── plugins/                  # 自定義插件 (modifier, function, block)
├── templates/                    # 模板文件 (.tpl)
├── templates_c/                  # 編譯緩存 (需寫入權限)
├── cache/                        // 靜態緩存 (需寫入權限)
└── configs/                      // 配置文件 (.conf)

快速入門

require_once 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->setTemplateDir('templates/');
$smarty->setCompileDir('templates_c/');
$smarty->setCacheDir('cache/');
$smarty->setConfigDir('configs/');

// 開發環境:強制編譯、關閉緩存
$smarty->force_compile = true;
$smarty->caching = false;

// 生產環境:關閉強制編譯、開啟緩存
// $smarty->force_compile = false;
// $smarty->caching = true;
// $smarty->cache_lifetime = 3600;

// 分界符修改 (避免與 JS/Vue/React {{ }} 衝突)
$smarty->left_delimiter  = '{';
$smarty->right_delimiter = '}';

// 分配變量
$smarty->assign('name', '張三');
$smarty->assign('users', [
    ['name' => '李四', 'age' => 25],
    ['name' => '王五', 'age' => 30],
]);

// 顯示模板
$smarty->display('index.tpl');

模板語法精華

變量輸出

{$name}                    // 簡單變量
{$user.name|escape}        // 修飾器:HTML 轉義
{$user.name|default:'游客'} // 默認值
{$arr.0} / {$arr.key}      // 數組/對象訪問

流程控制

{if $user.logged}
  歡迎 {$user.name}
{elseif $user.banned}
  賬號已封禁
{else}
  登入
{/if}

{foreach $users as $u}
  
  • {$u.name} ({$u.age})
  • {foreachelse}
  • 暫無用戶
  • {/foreach} {section name=i start=0 loop=10 step=2} {$smarty.section.i.index} {/section}

    模板繼承 (Smarty 3 核心特性)

    {* layout.tpl *}
    
    {block name=title}默認標題{/block}
    
      {block name=content}默認內容{/block}
      {block name=footer}© 2024{/block}
    
    
    
    {* page.tpl *}
    {extends file="layout.tpl"}
    {block name=title}文章頁 - {$title}{/block}
    {block name=content}
      
    {$content}
    {/block}

    緩存控制

    {* 整頁緩存 *}
    {$smarty->caching = true;}
    
    {* 局部不緩存 *}
    {nocache}
      {$user.name}  {* 每次動態獲取 *}
    {/nocache}
    
    {* 模板內指定緩存時間 *}
    {cache lifetime=300} ... {/cache}
    

    自定義插件開發

    在 plugins/ 下建立 modifier.truncate.php:

    function smarty_modifier_truncate($string, $length = 80, $etc = '...', $breakWords = false) {
        if (mb_strlen($string) <= $length) return $string;
        return mb_substr($string, 0, $length) . $etc;
    }
    

    模板中使用:{$longText|truncate:50:'...'}

    進階配置技巧

    • 多模板目錄:$smarty->addTemplateDir(['frontend' => 'templates/frontend/', 'admin' => 'templates/admin/']),模板引用 frontend:index.tpl。
    • 多編譯/緩存目錄分離:多站點共用核心庫時隔離緩存。
    • 註冊模板函數/類:$smarty->registerPlugin('function', 'url', 'my_url_func'),模板中 {url route='user' id=1}。
    • 安全策略:$smarty->security_policy = new Smarty_Security($smarty); 限制 PHP 標簽、文件包含、目錄遍歷。

    常見坑與避坑

    1. 模板變量未轉義導致 XSS:預設不轉義,務必 |escape 或啟用 $smarty->escape_html = true (Smarty 3.1+)。
    2. 緩存未失效:修改模板/配置後需手動清空 templates_c/ cache/ 或設置 force_compile = true。
    3. 分界符衝突:前端框架使用 {{ }} 時,修改 Smarty 分界符為 { } 或 {% %}。
    4. 大數據集渲染慢:避免在模板中循環調用複雜邏輯,預先在 PHP 處理好數據結構再 assign。

    結語

    Smarty 以編譯緩存、模板繼承、插件機制、安全策略見長,是 PHP 傳統 MVC 專案的優秀選型。現代項目亦可配合前端框架(Vue/React)採用「後端渲染首屏 + 前端接管」混合模式,Smarty 負責首屏 SEO 與初始狀態輸出。

    copyright © 萬盛學電腦網 all rights reserved