在模板中需要隨機數時,不必從 PHP 傳遞,Smarty 內建 {math} 函數即可直接產生。本文介紹 math 函數用法與隨機數產生技巧。
{math equation=rand(125,324)}
{math equation="運算式" 變數=值 ... [format="格式"] [assign="變數名"]}
+, -, *, /, abs, ceil, cos, exp, floor, log, log10, max, min, pi, pow, rand, round, sin, sqrt, srand, tan
equation:數學運算式,可使用變數format:輸出格式(sprintf 格式,如 "%.2f")assign:指定輸出賦值給模板變數,而非直接顯示| 程式碼 | 說明 | 輸出 |
|---|---|---|
{math equation="x + y" x=4 y=5} | 基本加法 | 9 |
{math equation="height * width / division" height=10 width=20 division=2} | 複合運算 | 100 |
{math equation="((x + y) / z)" x=2 y=10 z=2} | 括號優先序 | 6 |
{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"} | 格式化小數 | 9.44 |
{math equation="rand(1,100)" assign="rand_num"} | 指派變數 | (不輸出,{$rand_num} 可用) |
注意:math底層使用 PHPeval(),執行效率較低。大量運算或高頻頁面建議在 PHP 控制器預先計算,再指派給模板。