Smarty 是 PHP 經典的模板引擎,嚴格分離業務邏輯與表現層。本文從下載安裝、核心配置、目錄結構到常用變數調節器(修飾符),提供完整上手指南。
smarty,置於專案目錄。templates/ — 模板檔templates_c/ — 編譯快取temp/ / cache/ — 快取目錄configs/ — 設定檔smarty.inc.php<?php
require_once 'smarty/Smarty.class.php';
$smarty = new Smarty();
// 目錄配置
$smarty->template_dir = 'templates/';
$smarty->compile_dir = 'templates_c/';
$smarty->cache_dir = 'temp/';
$smarty->config_dir = 'configs/';
// 快取設定(開發階段建議關閉)
$smarty->caching = 0; // 0=關閉, 1=開啟
$smarty->cache_lifetime = 60; // 快取壽命(秒)
// 網站根網址常數
if (!defined('SITE_URL')) {
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
define('SITE_URL', $url);
}
// 專案根目錄常數
if (!defined('__ROOT__')) {
define('__ROOT__', rtrim(dirname(__FILE__), '\\') . '\\');
}
// Magic Quotes 相容處理(PHP 5.4+ 已移除,視版本決定是否保留)
if (get_magic_quotes_gpc()) {
function stripcslashes_arr($array) {
return is_array($array) ? array_map('stripcslashes_arr', $array) : stripslashes($array);
}
$_POST = stripcslashes_arr($_POST);
$_GET = stripcslashes_arr($_GET);
$_REQUEST = stripcslashes_arr($_REQUEST);
$_COOKIE = stripcslashes_arr($_COOKIE);
$_SESSION = stripcslashes_arr($_SESSION);
}
// 時區設定
date_default_timezone_set('PRC'); // 中國標準時間
// 載入通用函式庫
if (file_exists('common/common.php')) {
require_once 'common/common.php';
}
?>
index.php<?php
require_once 'smarty.inc.php';
// 指派單一變數
$title = '第一個標題';
$smarty->assign('title', $title);
// 指派陣列資料(volist 迴圈用)
$people = array(
array('name' => '張三', 'sex' => '男', 'age' => '20'),
array('name' => '李四', 'sex' => '男', 'age' => '40'),
array('name' => '王五', 'sex' => '女', 'age' => '32'),
);
$smarty->assign('people', $people);
// 輸出模板
$smarty->display('index.tpl');
?>
templates/index.tpl<html>
<head><title>{$title}</title></head>
<body>
<h1>{$title}</h1>
<table border="1">
<tr><th>姓名</th><th>性別</th><th>年齡</th></tr>
{volist name=$people id=vo}
<tr>
<td>{$vo.name}</td>
<td>{$vo.sex}</td>
<td>{$vo.age}</td>
</tr>
{/volist}
</table>
</body>
</html>
| 調節器 | 說明 | 範例 | 輸出 |
|---|---|---|---|
capitalize | 首字母大寫 | {$name|capitalize} | Hello World |
upper/lower | 全大寫/全小寫 | {$name|upper} | HELLO WORLD |
truncate:30:"..." | 截斷至 30 字元,尾端加 ... | {$longText|truncate:30:"..."} | 這是一段很長的文字... |
strip_tags | 移除 HTML 標籤 | {$html|strip_tags} | 純文字內容 |
escape:"html" | HTML 實體編碼(防 XSS) | {$input|escape:"html"} | <script>...</script> |
date_format:"%Y-%m-%d" | 日期格式化(需 Unix 時間戳) | {$timestamp|date_format:"%Y-%m-%d"} | 2024-01-15 |
default:"預設值" | 變數為空時顯示預設值 | {$var|default:"無資料"} | 無資料 |
indent:4 | 每行縮排 4 空格 | {$text|indent:4} | (程式碼顯示用) |
replace:"搜尋":"替換" | 字串替換 | {$str|replace:"old":"new"} | new content |
regex_replace:"pattern":"replace" | 正則替換 | {$str|regex_replace:"/\d+/":"[NUM]"} | 價格: [NUM] 元 |