Smarty 是經典的 PHP 模板引擎,核心優勢在於「業務邏輯與表現層分離」。本文通過一個最簡單的範例,展示 Smarty 目錄結構、配置初始化、變數指派、模板語法 (輸出、迴圈) 等核心用法。
project/
├── libs/ # Smarty 核心庫 (Smarty.class.php 等)
├── templates/ # 模板檔 (*.html, *.tpl)
├── templates_c/ # 編譯後的 PHP 檔案 (需寫入權限)
├── configs/ # 設定檔 (可選)
├── cache/ # 快取檔 (需寫入權限)
└── index.php # 入口腳本
index.php<?php
// 1. 載入 Smarty 核心類別
require_once __DIR__ . '/libs/Smarty.class.php';
// 2. 實例化
$smarty = new Smarty();
// 3. 設定目錄路徑 (建議使用絕對路徑)
$smarty->template_dir = __DIR__ . '/templates/';
$smarty->compile_dir = __DIR__ . '/templates_c/';
$smarty->config_dir = __DIR__ . '/configs/';
$smarty->cache_dir = __DIR__ . '/cache/';
// 4. 指派變數
$smarty->assign('content', 'Welcome to Smarty!');
$smarty->assign('mylife', ['生活', '吃飯', '夢想', '涼風']);
// 5. 顯示模板
$smarty->display('kk.html');
?>
templates/kk.html<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Smarty 入門範例</title>
</head>
<body>
<h1>{$content}</h1>
<h2>我的生活關鍵字:</h2>
<ul>
{section name=truelife loop=$mylife}
<li>{$mylife[truelife]}</li>
{/section}
</ul>
</body>
</html>
| 語法 | 說明 |
|---|---|
{$var} | 輸出變數 (自動轉義取決於設定) |
{section name=foo loop=$arr}...{/section} | 迴圈陣列,$arr 可為索引或關聯陣列 |
{$arr[foo]} | 在 section 中存取當前元素 |
{$smarty.get.id} | 直接存取 $_GET['id'] (亦有 post, cookies, server, env, session, request) |
{if $cond}...{elseif}...{else}...{/if} | 條件判斷 |
{include file="header.tpl"} | 引入子模板 |
<?php
// 開啟快取
$smarty->caching = true;
$smarty->cache_lifetime = 3600; // 秒
// 強制重新編譯 (開發環境)
$smarty->force_compile = true;
// 開啟錯誤報告 (開發環境)
$smarty->debugging = true;
// 變數修飾符範例 (模板中使用)
// {$name|upper} -> 大寫
// {$text|truncate:30} -> 截斷 30 字
// {$date|date_format:"%Y-%m-%d"} -> 格式化日期
// {$html|escape} -> HTML 轉義 (防 XSS)
?>
templates_c/ 與 cache/ 必須可由 Web 服務器使用者 (www-data, nginx 等) 寫入。掌握 Smarty 基礎用法,能快速構建結構清晰、易於維護的 PHP 應用,也是理解現代模板引擎設計思想的良好起點。