請求變數存取 {$smarty.*}
| 變數 | 來源 | 範例 |
{$smarty.get} | $_GET | {$smarty.get.id} |
{$smarty.post} | $_POST | {$smarty.post.name} |
{$smarty.cookies} | $_COOKIE | {$smarty.cookies.session_id} |
{$smarty.server} | $_SERVER | {$smarty.server.SERVER_NAME} |
{$smarty.env} | $_ENV | {$smarty.env.PATH} |
{$smarty.request} | $_REQUEST (合併) | {$smarty.request.username} |
{$smarty.session} | $_SESSION | {$smarty.session.user_id} |
其他常用保留變數
| 變數 | 用途 | 範例 |
{$smarty.now} | 當前 Unix 時間戳 | {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} |
{$smarty.const} | PHP 常數存取 | {$smarty.const.MY_CONST} |
{$smarty.capture} | 擷取輸出區塊 | {capture name=foo}...{/capture}{$smarty.capture.foo} |
{$smarty.config} | 設定檔變數 | {$smarty.config.foo} 等同 {#foo#} |
{$smarty.section} | section 迴圈屬性 | {$smarty.section.i.index} |
{$smarty.foreach} | foreach 迴圈屬性 | {$smarty.foreach.myloop.iteration} |
{$smarty.template} | 目前處理的模板名 | 除錯用 |
{$smarty.version} | Smarty 版本號 | 相容性檢查 |
{$smarty.ldelim} | 左分隔符 | 預設 { |
{$smarty.rdelim} | 右分隔符 | 預設 } |
實用範例
{* 顯示伺服器資訊 *}
Server: {$smarty.server.SERVER_NAME} (IP: {$smarty.server.SERVER_ADDR})
{* 格式化當前時間 *}
Current Time: {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}
{* 存取 PHP 定義常數 *}
App Version: {$smarty.const.APP_VERSION}
{* 擷取區塊輸出 *}
{capture name=sidebar}
<div class="sidebar">...</div>
{/capture}
{$smarty.capture.sidebar}
{* 迴圈屬性 *}
{section name=users loop=$users}
Row {$smarty.section.users.iteration}: {$users[users]}
{/section}
注意事項
{$smarty.request} 合併順序:GET → POST → COOKIE → SERVER → ENV,同名鍵後者覆蓋
- 模板中直接存取超全域變數略過控制器層,違反 MVC 分層,建議僅用於除錯或極簡專案
- 安全性:避免直接輸出
{$smarty.server.QUERY_STRING} 等未過濾資料