Smarty 不只是簡單的變數輸出,掌握其內建運算、保留變數與修飾符,能大幅減少 PHP 控制器邏輯,保持模板乾淨。
{$price + $tax}
{$quantity * $unitPrice}
{if ($total > 1000 && $user.level == 'VIP')}...{/if}
支援 + - * / %、邏輯比較、括號分組,優先級同 PHP。
| 模板語法 | 對應 PHP | 說明 |
|---|---|---|
{$smarty.get.page} | $_GET['page'] | URL 參數 |
{$smarty.post.username} | $_POST['username'] | 表單提交 |
{$smarty.cookies.auth} | $_COOKIE['auth'] | Cookie 值 |
{$smarty.server.REQUEST_URI} | $_SERVER['REQUEST_URI'] | 伺服器變數 |
{$smarty.session.user_id} | $_SESSION['user_id'] | Session 變數 |
{$smarty.request.keyword} | $_REQUEST['keyword'] | 合併 G/P/C |
{$smarty.env.PATH} | $_ENV['PATH'] | 環境變數 |
{$smarty.now|date_format:'%Y-%m-%d %H:%M:%S'}
{* 當前時間戳 *}
{$timestamp|date_format:'%Y/%m/%d'}
{* 自訂時間戳格式化 *}
{$smarty.const.APP_VERSION}
{$smarty.const.DB_HOST}
{* define('APP_VERSION', '1.2.3') 後可直接使用 *}
capture 區塊暫存輸出、config_load 載入設定檔