【smarty】smarty中自定义函数和自定义块
来源:互联网 发布:golang url encode 编辑:程序博客网 时间:2024/05/29 12:30
一、直接在控制器里面自定义一个普通函数<?php include_once("libs/Smarty.class.php"); // 包含smarty类文件 $smarty=new Smarty(); // 建立smarty实例对象$smarty /* $smarty->caching=false; // 是否使用缓存 $smarty->template_dir="./templates/"; // 设置模版目录 $smarty->compile_dir="./templates_c/"; //设置编译目录 $smarty->cache_dir="./smarty_cache/"; // 缓存文件夹 */ // 设置作用边界符 默认是{ } 一般用<{ }> $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.="<font color='".$args['color']."' size='".$args['size']."'>".$args['con']."</font>"."<br>"; } return $str; } // 注册一下 $smarty->register_function("hsp","test1"); $smarty->display("hello.tpl");?>模版中调用函数<{hsp times="10" size="5" color="green" con="hello,world"}>二、控制器中自定义一个块函数<?php include_once("libs/Smarty.class.php"); // 包含smarty类文件 $smarty=new Smarty(); // 建立smarty实例对象$smarty /* $smarty->caching=false; // 是否使用缓存 $smarty->template_dir="./templates/"; // 设置模版目录 $smarty->compile_dir="./templates_c/"; //设置编译目录 $smarty->cache_dir="./smarty_cache/"; // 缓存文件夹 */ // 设置作用边界符 默认是{ } 一般用<{ }> $smarty->left_delimiter="<{"; $smarty->right_delimiter="}>"; // 自定义一个函数(块方式) function test2($args,$con){ $str=""; for($i=0;$i<$args['times'];$i++){ $str.="<font color='".$args['color']."' size='".$args['size']."'>".$con."</font>"."<br>"; } 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的文件里面的代码如下<?phpfunction smarty_function_hsp($args, &$smarty){ $str=""; for($i=0;$i<$args['times'];$i++){ $str.="<font color='".$args['color']."' size='".$args['size']."'>".$args['con']."</font>"."<br>"; } 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的文件里面的代码如下<?phpfunction smarty_block_test($args, $con, &$smarty){ $str=""; for($i=0;$i<$args['times'];$i++){ $str.="<font color='".$args['color']."' size='".$args['size']."'>".$con."</font>"."<br>"; } return $str; }?>模版中直接调用 <{test times="10" size="5" color="yellow"}>hello,world<{/test}>