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

PHP Smarty 模板引擎完整學習指南:語法、變量、修飾符與內建函數詳解

     編輯:PHP 綜合知識

Smarty 模板引擎核心語法概覽

Smarty 是 PHP 中最經典的模板引擎之一,透過將邏輯與表現分離,大幅提升代碼可維護性。所有 Smarty 標籤皆包裹於定界符內(預設為 {}),定界符外的內容視為靜態輸出。開發者可自訂定界符,例如:

$smarty->left_delimiter  = '<!--{';
$smarty->right_delimiter = '}-->';

基礎語法元素

1. 註釋

模板註釋以 {* ... *} 包裹,不會輸出至前端,僅供模板內部參考。

2. 變量

  • 模板變量以 $ 開頭,支援字母、數字、底線組合。
  • 配置檔變量採用 #var# 格式引用。

3. 函數調用

Smarty 標籤可輸出變量或調用函數,語法統一為 {funcname attr1="val" attr2="val"}。內建函數(如 {if}、{section}、{strip})不可修改;自定義函數透過插件機制擴充,靈活度極高(如 {html_options}、{html_select_date})。

4. 屬性值規則

  • 靜態數值、布爾值(true/on/yes、false/off/no)無需引號。
  • 字串與變量引用不可加引號。

5. 字串內插入變量

僅識別英數字、底線及 [] 組合;複雜變量需用反引號包裹,如 {func var="test `$foo.bar` test"}。

6. 保留字輸出

需輸出定界符本身時,可用 {ldelim}/{rdelim}、{$smarty.ldelim}/{$smarty.rdelim} 或置於 {literal}...{/literal} 區塊中。

Smarty 保留變量 {$smarty}

{$smarty} 提供對特殊模板變量的存取:

  • 頁面請求變量:{$smarty.get}、{$smarty.post}、{$smarty.cookies}、{$smarty.server}、{$smarty.env}、{$smarty.session}、{$smarty.request}(綜合以上)。
  • 時間戳:{$smarty.now} 可搭配 date_format 修飾符格式化輸出。
  • PHP 常量:{$smarty.const.CONST_NAME}。
  • 捕獲輸出:{$smarty.capture.name} 對應 {capture name="name"}...{/capture}。
  • 配置變量:{$smarty.config.var} 等同 {#var#}。
  • 迴圈屬性:{$smarty.section.name}、{$smarty.foreach.name}。
  • 模板資訊:{$smarty.template}(當前模板名)、{$smarty.version}(版本號)、{$smarty.ldelim}/{$smarty.rdelim}(定界符)。

變量修飾符

修飾符以 | 套用,參數以 : 分隔。針對陣列變量時,預設逐元素處理;若需整體處理,在修飾符前加 @(如 {$arr|@count})。常用修飾符包括:

修飾符功能參數說明
capitalize單字首字大寫布林值決定含數字單字是否大寫,預設否
count_characters計算字元數布林值決定是否計算空格,預設否
cat字串連接參數為欲連接字串,預設空字串
count_paragraphs計算段落數無
count_sentences計算句子數無
count_words計算單字數無
date_format日期格式化第一參數為格式字串(支援 strftime 格式),第二參數為預設時間
default預設值變量為空或未賦值時輸出指定值
escape編碼轉義html、htmlall、url、quotes、hex、hexentity、javascript,預設 html
indent縮排第一參數縮排字元數(預設4),第二參數縮排字元(預設空格)
lower轉小寫無
nl2br換行轉 <br />無
regex_replace正則替換參數1:正則模式,參數2:替換字串
replace簡單搜尋替換參數1:被替換字串,參數2:替換字串
spacify字元間插入字串參數為插入字串,預設空格
string_format格式化浮點數sprintf 格式字串,如 %.2f
strip移除多餘空白參數為替換字串,預設單一空格
strip_tags移除 HTML 標籤無
truncate截斷字串參數1:長度(預設80),參數2:尾綴(預設...),參數3:是否精確截斷單字(預設false)
upper轉大寫無
wordwrap行寬限制參數1:寬度(預設80),參數2:斷行字元(預設\n),參數3:是否強制斷字(預設false)

內建函數

capture - 捕獲輸出

將區塊輸出存入變量而非直接顯示:{capture name="foo"}...{/capture},讀取用 {$foo} 或 {$smarty.capture.foo}。不可巢狀使用。

config_load - 載入配置檔

必填 file 指定檔名,section 指定區段,scope 設定作用域(local/parent/global,預設 local)。

foreach / foreachelse - 遍歷關聯陣列

簡易版 section,必填 from(來源陣列)、item(當前元素變量名),可選 key(鍵名)、name(迴圈名供屬性存取)。foreachelse 在陣列為空時執行。

include - 引入子模板

必填 file 指定模板,assign 將輸出存入變量。可自訂屬性傳遞區域變量。

include_php - 引入 PHP 腳本

file 指定路徑,once 控制是否僅載入一次(預設 true)。

insert - 動態插入 PHP 函數結果

name 指定函數名(實際調用 insert_name()),assign 存入變量,script 指定腳本路徑。結果不緩存,適合廣告、投票等動態內容。

if / elseif / else - 條件判斷

語法近似 PHP,運算子間需以空格分隔。新增運算子:eq、ne/neq、gt、lt、gte/ge、lte/le、not、mod、is [not] div by、is [not] even、is [not] odd。

php - 內嵌 PHP 代碼

{php}...{/php} 允許模板中直接撰寫 PHP,慎用。

section / sectionelse - 數值索引迴圈

必填 name(巢狀識別)、loop(迴圈次數)。支援 start、step、max、show 等屬性。迴圈屬性透過 {$smarty.section.name.var} 存取(index、iteration、first、last、total 等)。

strip - 移除多餘空白

{strip}...{/strip} 區塊內的重複空白、換行、Tab 將被壓縮。

常用自定義函數

  • assign:模板中賦值,必填 var、value。
  • counter:計數器,支援多實例(name)、初始值(start)、步長(skip)、方向(direction)、輸出控制(print)、存入變量(assign)。
  • cycle:循環輸出一組值,values 為值列表,delimiter 分隔符(預設逗號)。
  • debug:顯示所有已賦值變量,output 指定格式(html/javascript)。
  • eval:處理變量中的模板標籤,var 指定變量,assign 存入結果。
  • fetch:讀取檔案內容(本地/HTTP/FTP),file 指定路徑,assign 存入變量。
  • html_checkboxes / html_radios:產生複選框/單選框群,參數含 name、values、output、selected、options、separator、labels。
  • html_image:產生圖片標籤,自動偵測寬高,支援 basedir、href 等屬性。
  • html_options:產生下拉選單 options,參數同 checkboxes。
  • html_select_date / html_select_time:產生日期/時間選單,高度可配置(前綴、範圍、格式、順序、屬性等)。
  • html_table:依資料自動生成表格,控制行列、排列方向、屬性循環、填充等。
  • math:數學運算,equation 定義運算式(支援 + - * / abs ceil cos exp floor log log10 max min pi pow rand round sin sqrt tan 等),var 賦值變量,format 格式化結果,assign 存入變量。
  • mailto:郵件連結加密防爬蟲,encode 選擇 none/hex/javascript。
  • textformat:文字排版,控制縮排、行寬、換行字元、斷字規則。

核心常量與變量配置

常量/變量說明預設值
SMARTY_DIRSmarty 類別目錄完整路徑(須以 / 結尾)自動偵測
SMARTY_CORE_DIR核心檔案目錄SMARTY_DIR/core/
$template_dir模板目錄./templates
$compile_dir編譯目錄./templates_c
$config_dir配置檔目錄./configs
$plugins_dir插件目錄plugins
$debugging除錯主控台開關false
$debug_tpl除錯模板-
$debugging_ctrl除錯控制方式-
$autoload_filters全域過濾器陣列-
$compile_check每次執行檢查模板變更true
$caching啟用緩存false
$cache_dir緩存目錄./cache
$cache_lifetime緩存壽命(秒),-1 為永久3600

實際應用範例

<?php
error_reporting(7);
$TurnDot = substr(PHP_OS, 0, 3) == 'WIN' ? ';' : ':';
$doc_root = $_SERVER['DOCUMENT_ROOT'];
$lib_root = "." . $TurnDot . $doc_root . "/shopadmin" . $TurnDot . $doc_root . "/shopadmin/inc" . $TurnDot . $doc_root . "/" . $TurnDot . $doc_root . "/jpgraph/src/" . $TurnDot . $doc_root . "/Smarty/libs/" . $TurnDot . $doc_root . "/Smarty";
ini_set("include_path", $lib_root);
include("conf.global.php");
$Templates_root = $doc_root . "/templates";
define("Templates", $Templates_root);
$templates = isset($INFO['templates']) ? $INFO['templates'] : 'default';
include_once('Smarty.class.php');
$tpl = new Smarty();
$tpl->debugging = false;
$tpl->template_dir = Templates . "/" . $templates;
$tpl->compile_dir = Templates . "/" . $templates . "/templates_c";
$tpl->cache_dir = $doc_root . "/cache";
$tpl->cache_lifetime = 60 * 60 * 24;
$tpl->cache_lifetime = 0; // 開發階段關閉緩存
$tpl->caching = false;    // 上線前改為 true
$tpl->left_delimiter = '<{';
$tpl->right_delimiter = '}>';
$tpl->assign("template_dir", $INFO['site_url'] . "/templates/" . $templates);
$tpl->assign("Site_Url", $INFO['site_url']);
$tpl->assign("LanguageIs", $INFO['IS']);
$tpl->assign("HtmlTitle", $INFO['site_title']);
$tpl->assign("HtmlMeta", $INFO['meta_keyword']);
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved