smarty3使用自定义函数
smarty也像velocity一样支持自定义函数,smarty要使用自定义函数一般有两种方式一种就是写好方法后用smarty提供的注册机制完成,另一种就是把函数纳入到smarty的插件文件夹里。下面来分享下我的代码
1.使用注册机制完成自定义函数或函数块
要注意的是smarty3和smarty的区别,smarty2注册函数使用的是register_function函数块则使用register_block,对于smarty则统一使用registerPlugin,这个方法需要传入3个参数,第一个是类型支持function、block等具体参考开发文档,第二个是名称,第三个是我们定义的函数的名称。函数块使用的时候要像foreach那样有开始和结束标签
<?php require_once "libs/Smarty.class.php"; header("Content-type: text/html; charset=UTF-8"); $smart=new Smarty(); $smart->left_delimiter="<{"; $smart->right_delimiter="}>"; function jisuan($args){ if("+"==$args["type"]){ return $args["one"].$args["type"]. $args["two"]."=".($args["one"]+$args["two"]); }else if("-"==$args["type"]){ return $args["one"].$args["type"]. $args["two"]."=".($args["one"]-$args["two"]); } } function other($args,$type){ if("*"==trim($type)){ return $args["one"].$type. $args["two"]."=".($args["one"]*$args["two"]); }else if("/"==trim($type)){ return $args["one"].$type. $args["two"]."=".($args["one"]/$args["two"]); } } //注册插件(自定义函数) $smart->registerPlugin("function","jisuan","jisuan"); //注册插件(块的方式) $smart->registerPlugin("block","other","other"); $smart->display("userdefine.tpl"); ?>
下面就是模板代码了
<{*自定义函数块的使用*}> <{other one="8" two="10"}> * <{/other}></br> <{other one="8" two="10"}> / <{/other}></br> <{*自定义函数的使用*}> <{jisuan one=5 two=4 type="+"}></br> <{jisuan one=5 two=4 type="-"}></br>
2.无需注册的方式使用自定义函数或函数块
这种方式其实更简单只需把我们的函数写在libs下面的plugins目录下,但是要注意文件的命名要么是 function.函数名 如果是块的话是block.函数名 ,写在里面的方法命名也有规范
smarty_function_函数名 : 普通函数
smarty_block_函数名 :块函数
传入的参数也有要求,具体的不同smarty版本有不同的要求,具体可查看文档或打开plugins里面的php来弄 ,代码里就不用写registerPlugin了
<?php function smarty_function_jisuan($args, $template) { if("+"==$args["type"]){ return $args["one"].$args["type"]. $args["two"]."=".($args["one"]+$args["two"]); }else if("-"==$args["type"]){ return $args["one"].$args["type"]. $args["two"]."=".($args["one"]-$args["two"]); } }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: 使用Apache Http Server实现负载均衡并共享session
- 下一篇:没有了