smarty的自定义函数

自定函数的两种做法如下:

① 以手动注册的形式来添加自定义函数

1.1    写一个函数

function abc($args){
       //内容
       $args[‘color’]
}
//注册函数
$smarty->register_function(“myabc”,”abc”);

//可以在tpl文件中

<{myabc color=’’’}>

1.2    注册块函数

function abc2($args,$con){
       //处理代码
}
//注册块函数
$smary->register_block(“myfun2”,” abc2”);

//tpl文件

<{myfun2 属性1=”??” 属性2=”??” }>

hello,world

<{/myfun2}>

② 通过插件的形式来增加自定义函数(注:在smarty给出一个plugsin这个文件夹.)

//形式--文件名 function.???.php
 function smarty_function_???($args,&$smary){
}

//通过插件形式增加一个块.文件名 block.??,php
 function smarty_block_??($args,$con,&$smary){
       //写入代码
}

③例子

//自定义一个函数

 //tpl 调用形式{<dazhu times="4" size="5" con="hello" color="red" >}

 function fun1($args){
       $str="";
       for($i=0;$i<$args['times'];$i++){
            $str.="<br/><font color='".$args['color']."' size='".$args['size']."'>".$args['con']."</font>";
       }
            return $str
} //注册一下 $smarty->register_function("dazhu","fun1"); $smarty->display("test.tpl"); //tpl文件: <{dazhu times="10" con="hello,北京" color="blue" size="5"}>

我们把刚才的案例,演示块注册方式来完成

//tpl文件
<{dazhu times="10" color="blue" size="5"}>
hello,北京
<{/dazhu}>

//代码:
//自定义一个函数(块方式)
 function test2($args,$con){
       $str="";
         for($i=0;$i<$args['times'];$i++){
              $str.="<br/><font color='".$args['color']."' size='".$args['size']."'>".$con."</font>";
              }
              return $str;
       }

在smarty给出一个plugsin这个文件夹.

这里我们可以编写一个插件函数,但是这个函数名和文件名有一个规范,必须遵守.

文件名的格式: function.自定义函数名.php

函数的名字:

function smarty_function_自定义函数名($params, &$smarty){

//写码.

}

文件名的格式: block.块名.php

函数的名字:

function smarty_block_块($params, $content, &$smarty){

//写码.

}

我要青春像陈孝正一样,不能有一毫米的误差! 我要青春像合伙人一样,为了自尊而战!
原文地址:https://www.cnblogs.com/fanglove/p/3089945.html