首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 模板引擎保留變數完整參考手冊

     編輯:PHP 綜合知識

請求變數存取 {$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} 等未過濾資料
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved