smarty模板引擎_7-自定义函数

来源:互联网 发布:免费的php空间 编辑:程序博客网 时间:2024/04/26 14:29

扩展自定义函数的两种方式

1、通过registerPlugin()注册,仅对当前模板有效

[php] view plain copy
  1. function getVerify($params,$smarty){  
  2.     if(empty($params['type'])||$params['type']>3||$params['type']<1){  
  3.         $type=1;  
  4.     }else{  
  5.         $type=$params['type'];  
  6.     }  
  7.     if(empty($params['length'])||$params['length']>6||$params['length']<=0){  
  8.         $length=4;  
  9.     }else{  
  10.         $length=$params['length'];  
  11.     }  
  12.     if($type==1){  
  13.         //数字验证码  
  14.         $string=join('',range(0,9));  
  15.     }elseif($type==2){  
  16.         $string=join('',array_merge(range('a','z'),range('A','Z')));  
  17.     }elseif($type==3){  
  18.         $string=join('',array_merge(range(0,9),range('a','z'),range('A','Z')));  
  19.     }  
  20.     return substr(str_shuffle($string),0,$length);  
  21. }  
规定函数里需要用到的参数都要用$params这个数组传入

$smarty,Smarty的对象

[php] view plain copy
  1. $smarty->registerPlugin('function','verifyCode','getVerify');  

function表示是自定义函数

verifyCode是自定义函数的名称

getVerify自定义函数中的调用的函数


调用该自定义函数

[php] view plain copy
  1. <{verifyCode}>  
  2. <hr />  
  3. <{verifyCode type='2'}>  
  4. <hr />  
  5. <{verifyCode type='3' length='5'}>  

2、以插件形式扩展全局自定义函数

[php] view plain copy
  1. function smarty_function_verify($params,$smarty){  
  2.     if(empty($params['type'])||$params['type']>3||$params['type']<1){  
  3.         $type=1;  
  4.     }else{  
  5.         $type=$params['type'];  
  6.     }  
  7.     if(empty($params['length'])||$params['length']>6||$params['length']<=0){  
  8.         $length=4;  
  9.     }else{  
  10.         $length=$params['length'];  
  11.     }  
  12.     if($type==1){  
  13.         //数字验证码  
  14.         $string=join('',range(0,9));  
  15.     }elseif($type==2){  
  16.         $string=join('',array_merge(range('a','z'),range('A','Z')));  
  17.     }elseif($type==3){  
  18.         $string=join('',array_merge(range(0,9),range('a','z'),range('A','Z')));  
  19.     }  
  20.     return substr(str_shuffle($string),0,$length);  
  21. }  
函数命名规则:smarty_function_verify($params,$smarty){}

插件命名规则:function.verify.PHP

插件目录:plugins文件夹

调用该插件

[php] view plain copy
  1. <{verify}>  
  2. <hr />  
  3. <{verify type='2'}>  
  4. <hr />  
  5. <{verify type='3' length='5'}>  
0 0
原创粉丝点击