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

Smarty 模板引擎安裝與配置完整教學 (目錄結構、分隔符、緩存、測試)

     編輯:PHP 相關知識

Smarty 模板引擎安裝與配置完整教學

Smarty 是 PHP 經典的模板引擎,將業務邏輯與視圖分離。雖然現代框架內建模板引擎 (Blade, Twig, Latte),但在維護舊專案或輕量專案時,Smarty 仍是穩定選擇。

Step 1:下載與解壓

Step 2:目錄結構規劃 (手動安裝時)

project_root/
├── libs/              # Smarty 核心類別 (從套件複製)
│   └── Smarty.class.php
├── templates/         # 模板檔 (.tpl/.html)
├── templates_c/       # 編譯後檔案 (需可寫入)
├── cache/             # 快取檔案 (需可寫入)
├── configs/           # 設定檔 (可選)
├── smarty_config.php  # Smarty 初始化配置
└── index.php          # 入口腳本

Step 3:建立 Smarty 配置檔 (smarty_config.php)

<?php
require_once __DIR__ . '/libs/Smarty.class.php';

$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->cache_lifetime = 3600; // 快取壽命(秒)

// 設定分隔符 (避免與 JS 框架 {{ }} 衝突)
$smarty->left_delimiter  = '<{';
$smarty->right_delimiter = '}>';

// 除錯模式 (開發環境)
$smarty->debugging = false;

// 錯誤處理
$smarty->error_reporting = E_ALL & ~E_NOTICE;

return $smarty;

Step 4:設定目錄權限 (Linux)

# templates_c 與 cache 需 Web 伺服器可寫入
sudo chown -R www-data:www-data templates_c cache
sudo chmod -R 775 templates_c cache

Step 5:建立測試模板 (templates/index.tpl)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Smarty 測試</title>
</head>
<body>
    <h1><{$title}></h1>
    <p>當前時間:<{$current_time}></p>
    <ul>
    {foreach $items as $item}
        <li><{$item}></li>
    {/foreach}
    </ul>
</body>
</html>

Step 6:入口腳本測試 (index.php)

<?php
require_once __DIR__ . '/smarty_config.php';

// 指派變數
$smarty->assign('title', 'Smarty 安裝成功!');
$smarty->assign('current_time', date('Y-m-d H:i:s'));
$smarty->assign('items', ['蘋果', '香蕉', '橘子', '葡萄']);

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

進階配置建議

  • 自動載入:Composer 安裝時直接 require 'vendor/autoload.php'; 即可使用 Smarty 類別。
  • 模板繼承:使用 {block}、{extends} 實現佈局復用。
  • 快取策略:正式環境開啟 caching = true,搭配 cache_id 區分用戶/頁面。
  • 安全性:$smarty->security_policy 限制模板可用 PHP 函數、類別。
  • 插件擴展:自訂修飾詞、函數、區塊函數置於 plugins/ 目錄。

常見問題

  1. 白畫面/錯誤 500:檢查 templates_c/ cache/ 權限、PHP 錯誤日誌。
  2. 變數不顯示:確認分隔符設定一致、模板檔編碼為 UTF-8、變數名稱正確 (區分大小寫)。
  3. 中文亂碼:確保 PHP 檔、模板檔、資料庫連線皆為 UTF-8。
  4. 總結

    Smarty 安裝配置核心在於:正確引入核心類別、設定四大目錄路徑與權限、配置分隔符避免衝突。掌握這些基本功,即可在專案中穩定使用 Smarty 進行模板開發。

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