流程控制
foreach 進階屬性
{foreach $items as $item name=foo}
{$smarty.foreach.foo.index} {* 從 0 開始的索引 *}
{$smarty.foreach.foo.iteration} {* 從 1 開始的循環次數 *}
{$smarty.foreach.foo.first} {* 是否第一項 *}
{$smarty.foreach.foo.last} {* 是否最後一項 *}
{$smarty.foreach.foo.total} {* 總項數 *}
{/foreach}
{* 每 5 行輸出表頭 *}
{foreach $items as $i name=row}
{if $smarty.foreach.row.index % 5 == 0}| Title |
{/if}
| {$i.label} |
{/foreach}
section 嵌套與屬性
{* 外層 section *}
{section name=cat loop=$categories}
{$categories[cat].name}
{* 內層 section *}
{section name=item loop=$categories[cat].products}
{$categories[cat].products[item].title} - {$categories[cat].products[item].price}
{/section}
{/section}
{* section 屬性 *}
{$smarty.section.cat.index} {* 當前索引 *}
{$smarty.section.cat.iteration} {* 循環次數 *}
{$smarty.section.cat.first} {* 首項 *}
{$smarty.section.cat.last} {* 尾項 *}
{$smarty.section.cat.total} {* 總循環數 *}
條件判斷
{if $user.role eq 'admin'}
管理員面板
{elseif $user.role eq 'editor'}
編輯面板
{else}
普通用戶
{/if}
{* 比較運算符:eq, ne, gt, lt, gte, lte, ===, !== *}
{* 邏輯運算符:and, or, not *}
系統保留變量 {$smarty.*}
| 變量 | 來源 | 示例 |
| {$smarty.get.page} | $_GET['page'] | URL ?page=foo |
| {$smarty.post.username} | $_POST['username'] | 表單提交 |
| {$smarty.cookies.session_id} | $_COOKIE['session_id'] | Cookie 讀取 |
| {$smarty.server.REQUEST_URI} | $_SERVER['REQUEST_URI'] | /path?query |
| {$smarty.env.PATH} | $_ENV['PATH'] | 系統環境變量 |
| {$smarty.session.user_id} | $_SESSION['user_id'] | Session 讀取 |
| {$smarty.request.keyword} | 合併 G/P/C/S/E | 統一入口獲取 |
| {$smarty.now} | time() | {$smarty.now|date_format:"%Y-%m-%d"} |
| {$smarty.const.MAX_UPLOAD} | PHP 常量 | define('MAX_UPLOAD', 10) |
| {$smarty.capture.blockName} | {capture} 內容 | {capture name=block}...{/capture} |
| {$smarty.config.site_name} | 配置文件變量 | {#site_name#} 等價 |
| {$smarty.template} | 當前模板文件名 | index.tpl |
| {$smarty.version} | Smarty 版本號 | 3.1.39 |
| {$smarty.ldelim} / {$smarty.rdelim} | 左右分隔符 | 默認 { / } |
實用技巧
1. 變量修飾器鏈式調用
{$title|strip_tags|truncate:50:"..."|escape:"html"|upper}
2. 模板繼承(Smarty 3+)
{* layout.tpl *}
{block name=content}{/block}
{* page.tpl *}
{extends file="layout.tpl"}
{block name=content}頁面內容
{/block}
3. 緩存控制
$smarty->caching = true;
$smarty->cache_lifetime = 3600; // 秒
{* 模板中禁用緩存 *}
{nocache}{$dynamic_content}{/nocache}
4. 變量作用域
{assign var=foo value="bar"}:模板級全局
{assign var=foo value="bar" scope=parent}:傳遞給父模板
{assign var=foo value="bar" scope=root}:傳遞給根模板
{assign var=foo value="bar" scope="global"}:PHP 端 $smarty->assign() 等價
調試技巧
// PHP 端
$smarty->debugging = true; // 彈出調試窗口
// 或模板中
{debug}
{debug output=html} {* 內嵌輸出 *}
性能優化清單
- 生產環境關閉
debugging、啟用 caching、compile_check = false、force_compile = false
- 使用
{include file="sub.tpl" cache_lifetime=300} 片段緩存
- 避免在模板中進行複雜邏輯運算,預先在 PHP 處理好再傳入
- 大數據集遍歷考慮
{section} 比 {foreach} 略快(避免創建迭代器對象)