/var/www/ ├── index.php ├── libs/ │ └── Smarty.class.php ├── templates/ │ └── test.htm ├── templates_c/ # 編譯快取 (chmod 777) ├── configs/ │ └── test.conf └── cache/ # 快取目錄 (chmod 777)
title = "Welcome to Smarty!" cutoff_size = 40 [setup] bold = true
<html>
<head><title>Smarty Test</title></head>
<body>
<H1>Hello, {$Name}</H1>
</body>
</html>
<?php
require 'libs/Smarty.class.php';
$smarty = new Smarty();
// 目錄設定 (可選,符合慣例可省略)
$smarty->template_dir = 'templates/';
$smarty->compile_dir = 'templates_c/';
$smarty->config_dir = 'configs/';
$smarty->cache_dir = 'cache/';
// 指派變數
$smarty->assign("Name", "Simon");
// 顯示模板
$smarty->display('test.htm');
?>
<html> <head><title>Smarty Test</title></head> <body> <H1>Hello, Simon</H1> </body> </html>
<?php /* Smarty version 2.6.22, created on 2009-03-19 13:20:00 compiled from test.htm */ ?> <html> <head><title>Smarty Test</title></head> <body> <H1>Hello, <?php echo $this->_tpl_vars['Name']; ?></H1> </body> </html>
new Smarty() 建立模板引擎assign() 將 PHP 變數傳遞給模板templates_c/$smarty->caching = true 可快取輸出 HTML$smarty->config_load('test.conf');
echo $smarty->get_config_vars('title'); // Welcome to Smarty!
$smarty->caching = true;
$smarty->cache_lifetime = 3600; // 1小時
if (!$smarty->is_cached('test.htm')) {
// 只有未快取時才做昂貴操作
$data = expensive_query();
$smarty->assign('data', $data);
}
$smarty->display('test.htm');
{* 內建函式 *}
{$name|upper}
{$date|date_format:"%Y-%m-%d"}
{$arr|@count}
{* 自訂函式 *}
{html_options values=$ids output=$names selected=$selected}
{* layouts/main.htm *}
<html><body>{block name="content"}{/block}</body></html>
{* page.htm *}
{extends file="layouts/main.htm"}
{block name="content"}<h1>頁面內容</h1>{/block}
| 問題 | 原因 | 解決 |
|---|---|---|
| 空白頁/500錯誤 | templates_c/ 權限不足 | chmod 777 templates_c/ cache/ |
| 修改模板不生效 | 編譯快取未更新 | 刪除 templates_c/ 對應檔案或 $smarty->force_compile = true |
| 變數顯示為 Array | 陣列直接輸出 | 用 {$arr|@count} 或 {foreach} |
| 中文亂碼 | 編碼不一致 | 確保 PHP、模板、資料庫皆 UTF-8 |
Smarty\Smartycomposer require smarty/smarty{extends}/{block} 取代 {include} 重構{$var} 自動跳脫 (需關閉 $smarty->auto_escape = false 相容舊版)Smarty 是 PHP 經典模板引擎,掌握「指派→編譯→執行」核心流程,即可快速上手專案開發。