Smarty 是 PHP 經典的模板引擎,將業務邏輯與視圖分離。雖然現代框架內建模板引擎 (Blade, Twig, Latte),但在維護舊專案或輕量專案時,Smarty 仍是穩定選擇。
composer require smarty/smartyproject_root/ ├── libs/ # Smarty 核心類別 (從套件複製) │ └── Smarty.class.php ├── templates/ # 模板檔 (.tpl/.html) ├── templates_c/ # 編譯後檔案 (需可寫入) ├── cache/ # 快取檔案 (需可寫入) ├── configs/ # 設定檔 (可選) ├── smarty_config.php # Smarty 初始化配置 └── index.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;
# templates_c 與 cache 需 Web 伺服器可寫入 sudo chown -R www-data:www-data templates_c cache sudo chmod -R 775 templates_c cache
<!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>
<?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');
require 'vendor/autoload.php'; 即可使用 Smarty 類別。{block}、{extends} 實現佈局復用。caching = true,搭配 cache_id 區分用戶/頁面。$smarty->security_policy 限制模板可用 PHP 函數、類別。plugins/ 目錄。templates_c/ cache/ 權限、PHP 錯誤日誌。Smarty 安裝配置核心在於:正確引入核心類別、設定四大目錄路徑與權限、配置分隔符避免衝突。掌握這些基本功,即可在專案中穩定使用 Smarty 進行模板開發。