Smarty 是 PHP 經典模板引擎,本文整理 11 類最常用代碼段範例,涵蓋表單元素生成、計數器、迴圈控制、變數指派、遠端內容抓取、圖片輸出、日期時間選單、表格生成、數學運算、郵件連結、彈出視窗,可作為開發速查參考。
{* 下拉選單 *}
<select>
{html_options values=$cust_ids selected=$customer_id output=$cust_names}
</select>
{* 複選框 *}
{html_checkboxes values=$cust_ids checked=$customer_id output=$cust_names separator="<br/>"}
{* 單選鈕 *}
{html_radios values=$cust_ids checked=$customer_id output=$cust_names separator="<br/>"}
參數:values=值陣列、selected/checked=預設選中、output=顯示文字陣列、separator=分隔符。
{counter start=0 skip=2 print=true}
從 0 開始,每次遞增 2,直接輸出。
{section loop=$data}
<tr bgcolor="{cycle values='#eeeeee,#d0d0d0'}">
<td>{$data[rows]}</td>
</tr>
{/section}
cycle 輪替輸出指定值,常用於斑馬紋表格。
{assign var="name" value="Bob"}
The value of $name is {$name}. {* 輸出:The value of $name is Bob *}
{fetch file="https://www.myweather.com/68502/" assign="weather"}
支援 https://、ftp://、本地路徑,抓取內容存入變數。
{html_image file="../path/relative/to/currdir/pumpkin.jpg"
border="1" height="100" width="100" alt="圖片" href="1.html"}
{html_select_date} {* 年/月/日下拉 *}
{html_select_time} {* 時/分/秒下拉 *}
{html_table loop=$data cols=4 table_attr='border="0"' tr_attr=$tr td_attr=$td}
將一維陣列按指定列數渲染為表格,支援 row/col 屬性自定義。
{math equation="x + y" x=$height y=$width}
{mailto address="me@domain.com" text="send me some mail"}
{popup} {* 需先呼叫 popup_init *}
熟悉這些核心語法,能大幅提升 Smarty 模板開發效率,減少 PHP 邏輯滲入視圖層。