smarty模板引擎中自定义函数的方法

这篇文章主要介绍了smarty模板引擎中自定义函数的方法,实例分析了自定义函数的定义、注册及调用技巧,需要的朋友可以参考下

本文实例讲述了smarty 自定义函数方法,分享给大家供大家参考。具体如下:

本实例目的:输出 times 次 con的内容(输出4次hello world)

文件1代码如下:

  1. <?php
  2. //创建smarty对象
  3. require_once("./libs/Smarty.class.php");
  4. $smarty = new Smarty();
  5. //自定义一个函数
  6. //说明:(1)、$arr为一个数组;(2)、tpl调用形式{test times="4" size="5" con="hello,world" color="red"}
  7. function test($arr){
  8. $str = "";
  9. for($i=0;$i<$arr['times'];$i++){
  10. $str .= "<font size='".$arr['size']."' color='".$arr['color']."'>".$arr['con']."</font>";
  11. }
  12. return $str;
  13. }
  14. //注册函数 registerPlugin
  15. $smarty->registerPlugin("function","test","test");//第二个参数是模板文件调用的函数名称,可变;第三个参数是上面自定义的函数名称;相应于一个对应关系
  16. $smarty->display("temp.tpl");
  17. ?>

模板文件:temp.tpl

  1. <html>
  2. <h2>smarty自定义函数的使用</h2>
  3. {test times="3" con="hello world" size="3" color="green"}
  4. </html>

注意:smarty 3.1.8 已经不支持注册函数 register_function,应换成 registerPlugin