在smarty模板中调用PHP自定义函数【smarty2||smarty3】

大家都知道,在smarty中提供了许多在模板中使用的调节器,但是在很多时候,这些调节器无法提供我们需要的功能,这时候,我们就需要自己定义PHP函数,然后在模板中调用。

首先,谈谈在smarty2中的解决方法:

smarty2中提供了一个函数,register_function,在官方文档上它的原型为

void register_function(string name,                        mixed impl,                        bool cacheable,                        mixed cache_attrs);

我们可以使用该函数来动态注册在模板中使用的自定义函数,它的第一个参数是我们将在模板中使用的函数名,第二个参数是我们定义的PHP函数名,该参数既可以是一个包含函数名称的字符串,也可以是一个array(&$object,$method)数组,其中&$object是表示对象引用,$method表示该对象的方法,第三个和第四个参数在绝大多数情况下都可以省略。它的用法很简单:下面给出一个简单的例子并加以说明 

view plain

1.  //.php   

2.  function htmlcode($paras) {  

3.      extract($paras);  

4.      Return str_replace('/n/r','<br>',str_replace(' ',' ',$cont));  

5.   }  

6.  $smarty=new Smarty();  

7.  $smarty>register_function('format_content','htmlcode');  

8.  $smarty->display("list.html");  

 

view plain

1.  //list.html  

2.  <table width="500px" border="0" cellspacing="5" cellpadding="1" bgcolor="#add3ef">  

3.    {section name=reply loop=$content}  

4.      <tr bgcolor="#eff3ff">  

5.        <td>标题:{$content[reply].title} 用户:{$content[reply].user}</td>  

6.      </tr>  

7.      <tr bgcolor="#ffffff">  

8.          <td>内容:{format_content cont=$content[reply].content}</td>  

9.      </tr>  

10.  {/section}  

11.</table>  

在服务器端,也就是PHP文件中,我定义了自己所需的功能函数htmlcode函数,然后使用register_function函数将它注册到format_content中,其中,format_content就是在模板中使用的函数名,在模板中,我们使用{format_content 参数1 参数2 ……}来调用函数,其中函数名之后带的参数(参数12等等)被组合成一个数组作为实参传入到了PHP自定义函数中,本例中,cont参数被组合成只有一个元素的数组传入到了htmlcode函数中来进行调用,也就是说htmlcode的形参$paras是一个数组,它的每一个元素对应我们在模版中给它传递的一个参数。

说到这里,大家应该知道该如何使用了吧,好了,下面来谈谈在smarty3中的解决方法。

smarty3中,我尝试用register_function函数,可出现了function call 'register_function' is unknown or deprecated的错误,于是我查了一下官方的文档,发现register_function这个函数在smarty3中已经被淘汰了,取而代之的是一个名为registerPlugin的一个功能更为强大的函数,该函数的原型为

void registerPlugin(string type,                     string name,                     mixed callback,                     bool cacheable,                     mixed cache_attrs);

可以看到,该函数仅仅比register_function多了第一个参数,string type,那么该参数是做什么用的呢?文档上是这么定义的:

type defines the type of the plugin. Valid values are "function", "block", "compiler" and "modifier".

翻译过来也就是说该参数定义了插件的类型,有效值为"function""block""complier""modifier"中的一个,看到这里大家应该明白了吧,在register_function中,只能注册function这一种类型,而该函数可以注册四种类型,其余的用法和register_function基本一致。

list.html中,我们不需要改动,而仅仅需要在PHP文件中稍作改动:

view plain

1.   function htmlcode($paras) {  

2.      extract($paras);  

3.      Return str_replace('/n/r','<br>',str_replace(' ',' ',$cont));  

4.   }  

5.  $smarty=new Smarty();  

6.  $smarty->registerPlugin('function','format_content','htmlcode');  

7.  $smarty->display("list.html");  

posted @ 2013-09-14 21:26  陈小贤  阅读(583)  评论(0)    收藏  举报