十年網(wǎng)站開發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶 + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營維護(hù)+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
怎么在smarty模板引擎中自定義函數(shù)?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
輸出 times 次 con的內(nèi)容(輸出4次hello world)
代碼如下:
//創(chuàng)建smarty對(duì)象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();
//自定義一個(gè)函數(shù)
//說明:(1)、$arr為一個(gè)數(shù)組;(2)、tpl調(diào)用形式{test times="4" size="5" con="hello,world" color="red"}
function test($arr){
$str = "";
for($i=0;$i<$arr['times'];$i++){
$str .= "".$arr['con']."";
}
return $str;
}
//注冊函數(shù) registerPlugin
$smarty->registerPlugin("function","test","test");//第二個(gè)參數(shù)是模板文件調(diào)用的函數(shù)名稱,可變;第三個(gè)參數(shù)是上面自定義的函數(shù)名稱;相應(yīng)于一個(gè)對(duì)應(yīng)關(guān)系
$smarty->display("temp.tpl");
?>
模板文件:temp.tpl
smarty自定義函數(shù)的使用
{test times="3" con="hello world" size="3" color="green"}
注意:smarty 3.1.8 已經(jīng)不支持注冊函數(shù) register_function,應(yīng)換成 registerPlugin
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,的支持。