首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Smarty 模板引擎環境配置與入門實戰教程

     編輯:PHP 相關知識

前言:為什麼選擇 Smarty?

Smarty 是 PHP 歷史最悠久、生態最成熟的模板引擎之一,以「模板編譯為 PHP 代碼」的機制兼顧了開發體驗與執行效能。雖然現代框架多內建模板引擎(Blade、Twig、Lathe),但在維護老專案、快速原型、或無框架項目中,Smarty 依然是極佳選擇。本文將手把手帶你完成環境搭建、目錄規劃、第一個模板渲染,並解釋關鍵配置項含義。

一、下載與目錄結構規劃

以 Smarty 3.x 為例(舊版 2.x 已停止維護,建議直接用 3.x 或 4.x)。

項目根目錄/
├── public/                 # Web 公開目錄
│   └── index.php           # 入口文件
├── vendor/                 # Composer 依賴(推薦)
│   └── smarty/smarty/      # Smarty 庫文件
├── templates/              # 模板源文件(.tpl)
│   ├── index.tpl
│   └── layouts/
├── templates_c/            # 編譯緩存(需可寫)
├── cache/                  # 模板緩存(需可寫)
└── configs/                # 配置文件(可選)

關鍵點:templates_c 與 cache 目錄必須授予 PHP 進程寫入權限(Linux: chmod 775 + 同群組)。

二、Composer 安裝(推薦)

composer require smarty/smarty ^4.0

若不使用 Composer,請從 官網 下載壓縮包,解壓後將 libs/ 目錄放入項目(如 vendor/smarty/)。

三、入口文件配置與第一個模板

1. public/index.php

<?php
require_once __DIR__ . '/../vendor/autoload.php'; // Composer 自動加載

use Smarty\Smarty;

$smarty = new Smarty();

// 目錄配置(絕對路徑最安全)
$smarty->setTemplateDir(__DIR__ . '/../templates');
$smarty->setCompileDir(__DIR__ . '/../templates_c');
$smarty->setCacheDir(__DIR__ . '/../cache');
$smarty->setConfigDir(__DIR__ . '/../configs');

// 開發環境關閉緩存,生產環境開啟
$smarty->caching = false; // 生產建議 true
$smarty->force_compile = true; // 開發階段強制重新編譯

// 自定義分隔符,避免與 JS { } 衝突
$smarty->left_delimiter  = '{#';
$smarty->right_delimiter = '#}';

// 賦值變量
$smarty->assign('hello', 'Hello Smarty!');
$smarty->assign('user', ['name' => '張三', 'role' => '管理員']);

// 渲染輸出
$smarty->display('index.tpl');

2. templates/index.tpl

<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <title>Smarty 入門示例</title>
</head>
<body>
    <h1>{#$hello#}</h1>
    <p>歡迎,{#$user.name#}({#$user.role#})</p>
    
    <!-- 模板邏輯示例 -->
    {#if $user.role == '管理員'#}
        <span style="color:red">[後台入口]</span>
    {#/if#}
</body>
</html>

四、核心配置項詳解

屬性/方法說明建議值
setTemplateDir模板源文件目錄(可為陣列支援多主題)絕對路徑
setCompileDir編譯後的 PHP 文件存放目錄(必須可寫)絕對路徑
setCacheDir模板緩存目錄(caching=true 時使用)絕對路徑
caching是否啟用模板輸出緩存開發 false,生產 true
force_compile每次請求強制重新編譯(開發便利)開發 true,生產 false
left/right_delimiter模板標籤分隔符,預設 { } 易與 JS 衝突推薦 {# #} 或 <{ }>
escape_html全局自動轉義變量輸出(防 XSS)Smarty 3.1+ 建議 true

五、常見進階用法速覽

  • 模板繼承:{block name='title'}{/block} + {extends 'layout.tpl'} 實現佈局復用。
  • 配置文件:{config_load file='colors.conf'} 讀取 key = "value" 格式文件,模板中用 {#key#} 或 {$smarty.config.key} 調用。
  • 內建修飾符:{$name|upper|truncate:20:'...'} 串聯處理變量。
  • 自定義函數/修飾符:$smarty->registerPlugin('modifier', 'my_filter', 'my_filter_func');。
  • 緩存組/過期時間:$smarty->display('index.tpl', 'cache_group_1'); + $smarty->clearCache('index.tpl', 'cache_group_1');。

六、避坑指南

  1. 權限問題:templates_c/cache 權限不足是部署最常見報錯。
  2. 分隔符衝突:未修改分隔符直接在模板寫 JS 物件 {foo: 'bar'} 會報錯。
  3. 編碼不一致:模板文件、PHP 文件、資料庫連線、HTML meta 均需統一 UTF-8。
  4. 緩存未清理:修改模板後頁面不更新,請檢查 force_compile 或手動刪除 templates_c 內容。

結語

完成上述步驟,你已擁有一個可運行的 Smarty 環境。接下來可探索模板繼承、插件擴展、緩存策略等進階主題。Smarty 文檔詳盡,遇到問題優先查閱 官方手冊。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved