smarty自定义函数用法示例

2019-11-13,,,,

本文实例讲述了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.kunjuke.com/code/phpformat

JavaScript代码美化/压缩/格式化/加密工具:
http://tools.kunjuke.com/code/jscompress

在线XML格式化/压缩工具:
http://tools.kunjuke.com/code/xmlformat

JSON代码格式化美化工具:
http://tools.kunjuke.com/code/json

在线XML/JSON互相转换工具:
http://tools.kunjuke.com/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.kunjuke.com/code/jsoncodeformat

sql代码在线格式化美化工具:
http://tools.kunjuke.com/code/sqlcodeformat

更多关于Smarty相关内容感兴趣的读者可查看本站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于smarty模板的PHP程序设计有所帮助。

《smarty自定义函数用法示例.doc》

下载本文的Word格式文档,以方便收藏与打印。