本文實例講述了smarty自定義函數用法。分享給大家供大家參考,具體如下:
<?php
require_once "smarty.config.php";
//自定義一個函數
//調用方法:<{test1 times="4" size="5" con="Hello,Liuyibao!" color="red"}>
function test1($args){
$str="";
for($i=0;$i<$args['times'];$i++){
$str.="<p style='font-size:{$args['size']}em;color:{$args['color']}'>{$args['con']}</p>";
}
return $str;
}
//自定義一個塊方式函數
//調用方法<{test1}><{/test1}>
function test2($args,$con){
$str="";
for($i=0;$i<$args['times'];$i++){
$str.="<p style='font-size:{$args['size']}em;color:{$args['color']}'>{$con}</p>";
}
return $str;
}
//定義一個計算方法
function jisuan($args){
switch($args['operate']){
case "+" :$res=$args['num1']-$args['num2'];break;
case "-" :$res=$args['num1']-$args['$num2'];break;
case "*" :$res=$args['num1']*$args['$num2'];break;
case "/" :$res=$args['num1']/$args['$num2'];break;
}
return $res;
}
//注冊一下
$smarty->register_function("liuyibao","test1");
//注冊塊函數
$smarty->register_block("liuyibao2","test2");
//注冊函數jisuan
$smarty->register_function("jisuan","jisuan");
//替換變量
$smarty->display("function.tpl");
?>
PS:這裡推薦幾款本站的格式化/美化/轉換工具可以幫助你整理雜亂無章的代碼,相信大家在以後的開發中能夠用得上:
php代碼在線格式化美化工具:
http://tools.jb51.net/code/phpformat
JavaScript代碼美化/壓縮/格式化/加密工具:
http://tools.jb51.net/code/jscompress
在線XML格式化/壓縮工具:
http://tools.jb51.net/code/xmlformat
JSON代碼格式化美化工具:
http://tools.jb51.net/code/json
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.jb51.net/code/jsoncodeformat
sql代碼在線格式化美化工具:
http://tools.jb51.net/code/sqlcodeformat
更多關於Smarty相關內容感興趣的讀者可查看本站專題:《smarty模板入門基礎教程》、《PHP模板技術總結》、《PHP基於pdo操作數據庫技巧總結》、《PHP運算與運算符用法總結》、《PHP網絡編程技巧總結》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基於smarty模板的PHP程序設計有所幫助。