Smarty 是 PHP 歷史上最流行的模板引擎之一,其核心理念是「強制分離業務邏輯(PHP)與展示邏輯(HTML)」。本文通過最簡潔的代碼演示 Smarty 核心工作流:配置初始化 → 變量賦值 → 模板渲染。
libs/Smarty.class.php 放入項目可訪問路徑templates/、templates_c/、configs/、cache/<?php
// index.php
header("Content-Type: text/html; charset=UTF-8");
// 1. 載入核心類
require_once '../libs/Smarty.class.php';
// 2. 實例化
$smarty = new Smarty();
// 3. 目錄配置(關鍵步驟)
$smarty->template_dir = 'templates/'; // 模板文件目錄
$smarty->compile_dir = 'templates_c/'; // 編譯緩存目錄(需寫入權限)
$smarty->config_dir = 'configs/'; // 配置文件目錄
$smarty->cache_dir = 'cache/'; // 緩存目錄(需寫入權限)
// 4. 賦值變量
$smarty->assign('content', 'welcome to arrival');
$smarty->assign('mylife', ["生活", "吃飯", "夢想", "涼風"]);
// 5. 顯示模板
$smarty->display('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>
<ul>
{section name=truelife loop=$mylife}
<li>{$mylife[truelife]}</li>
{/section}
</ul>
</body>
</html>
welcome to arrival
• 生活
• 吃飯
• 夢想
• 涼風
| 概念 | 說明 | 對應代碼 |
|---|---|---|
| template_dir | 存放 .html/.tpl 模板文件 | templates/ |
| compile_dir | 存放編譯後的 PHP 文件(自動生成) | templates_c/ |
| config_dir | 存放 .conf 配置文件(可選) | configs/ |
| cache_dir | 存放緩存文件(開啟 caching 後使用) | cache/ |
| assign() | PHP 向模板傳遞變量 | $smarty->assign('key', $val) |
| display() | 渲染並輸出模板 | $smarty->display('file.html') |
{$var}、{$arr.key}、{$obj->prop}{section name=i loop=$arr}{$arr[i]}{/section}{if $cond}...{elseif $cond}...{else}...{/if}{$var|upper}、{$var|escape}、{$var|truncate:20}{html_options}、{html_select_date}、{counter}| 配置項 | 開發環境 | 生產環境 |
|---|---|---|
$smarty->force_compile | true (每次重新編譯) | false |
$smarty->caching | false | true |
$smarty->cache_lifetime | 0 | 3600 (秒,視業務而定) |
$smarty->compile_check | true | false |
{extends 'layout.tpl'} + {block name='content'}{/block} (Smarty 3+)Smarty 雖非現代框架首選(如 Laravel Blade、Twig),但在維護老項目、快速原型、非框架項目中仍具極高實用價值。掌握其核心工作流,能快速上手各類基於 Smarty 的歷史項目。