Smarty自定义函数实例解析

一、直接在控制器里面自定义一个普通函数
   include_once("libs/Smarty.class.php");   // 包含smarty类文件
   $smarty=new Smarty();   // 建立smarty实例对象$smarty
   
   //  设置作用边界符  默认是{  }  一般用<{ }>
   $smarty->left_delimiter="<{";
   $smarty->right_delimiter="}>";

   // 自定义一个函数
   //  模版调用形式  <{hsp times="10" size="5" color="red" con="hello,world"}>
 function test1($args){
  $str="";
  for($i=0;$i<$args['times'];$i++){
  $str.="".$args['con'].""."
";
  }
  return $str;
   }
   // 注册一下
   $smarty->register_function("hsp","test1");
   $smarty->display("hello.tpl");
模版中调用函数
<{hsp times="10" size="5" color="green" con="hello,world"}>
二、控制器中自定义一个块函数
   include_once("libs/Smarty.class.php");   // 包含smarty类文件
   $smarty=new Smarty();   // 建立smarty实例对象$smarty
   
   //  设置作用边界符  默认是{  }  一般用<{ }>
   $smarty->left_delimiter="<{";
   $smarty->right_delimiter="}>";

   //  自定义一个函数(块方式)
   function test2($args,$con){
  $str="";
  for($i=0;$i<$args['times'];$i++){
  $str.="".$con.""."
";
  }
  return $str;
   }
   //注册块函数
   $smarty->register_block("fun","test2");
   $smarty->display("hello.tpl");
模版中以块方式调用函数
<{fun times="10" size="5" color="red"}>
hello,world
<{/fun}>

三、以插件的形式增加自定义函数
   如何以插件的形式增加自定义函数   在libs/plugins文件夹下 建立一个php文件  
   这里我们可以编写一个插件函数,但是这个函数名和文件名有一个规范,必须遵守
   文件名的格式:function.自定义函数名.php   例如:function.eqv.php
   第二个参数必须写&$smarty   第一个可以自己定义   例如:function smarty_function_eqv($params, &$smarty)
   函数的名字:function smarty_function_自定义函数名($params, &$smarty){     
                 写代码
   }
例如:在libs/plugins文件夹下建立一个名为function.hsp.php的文件
里面的代码如下


function smarty_function_hsp($args, &$smarty){
  $str="";
  for($i=0;$i<$args['times'];$i++){
  $str.="".$args['con'].""."
";
  }
  return $str;
}
?>
模版中直接调用 
<{hsp times="10" size="5" color="green" con="hello,world"}>

四、以插件的形式定义块

这里以块的方式增加一个插件,这里同样要保持名字的规范
文件名的格式:block.块名.php   例如:function.eqv.php
函数的名字:function smarty_block_块名($params,$content, &$smarty){    
例如:在libs/plugins文件夹下建立一个名为 block.test.php的文件
里面的代码如下

function smarty_block_test($args, $con, &$smarty){
  $str="";
  for($i=0;$i<$args['times'];$i++){
  $str.="".$con.""."
";
  }
  return $str;
   }

模版中直接调用 
<{test times="10" size="5" color="yellow"}>
hello,world
<{/test}>
posted @ 2014-03-31 14:06  张三_zhangsan  阅读(535)  评论(0编辑  收藏  举报