myfun.tpl
自定義函數 自定義函數的使用配置
<{*這是注釋*}>
<{myfun times="10" con="Hello world, this is user defined function!" color="red" size="5"}>
now time is <{date_now format="%Y/%m/%d"}> <{*下面是自定義塊函數調用*}>
下面是塊標簽
<{blockTest times="10" color="green" size="5"}> Hello world,this is block function test! <{/blockTest}>
"' ); $smarty = new Smarty (); $smarty->left_delimiter = "<{"; $smarty->right_delimiter = "}>"; // 注冊plugin函數中的三個參數 // type defines the type of the plugin. Valid values are "function", "block", "compiler" and "modifier". // name defines the name of the plugin. // callback defines the PHP callback. it can be either: $smarty->registerPlugin ( "function", "myfun", "myfun" ); function myfun($args) { $str = ""; for($i = 0; $i < $args ['times']; $i ++) { $str .= "" . $args ['con'] . "
"; } return $str; } $smarty->registerPlugin ( "function", "date_now", "print_current_date" ); function print_current_date($params, $smarty) { if (empty ( $params ["format"] )) { $format = "%b %e, %Y"; } else { $format = $params ["format"]; } return strftime ( $format, time () ); } $smarty->registerPlugin ( "block", "blockTest", "blockTest" ); // 自定義函數(塊方式) function blockTest($args, $con) { $str = ""; // 此處注意為什麼要加empty判斷,如果不加此判斷的話,在$con為空的情況下,$str也會被輸出十次,從而造成頁面中有很多的空行,這種問題的原因是 // 因為smarty計算在前,你獲取數據在後,也就是說第一次時,$con已經被smarty計算過了(雖然$con沒有值),但是確實在smarty內部計算過了,而且之後也進行了輸出 if (! empty ( $con )) { for($i = 0; $i < $args ['times']; $i ++) { $str .= "" . $con . "
"; } } // echo $str; return $str; } $smarty->display ( "myfun.tpl" ); ?>