您的位置:首页 > 其它

smarty功能扩展,可以把自己需要的功能扩展出来

2011-11-16 15:19 393 查看
要实现对smarty的功能扩展,我们要知道smarty有内建函数和自定义函数。内建函数是smarty自带的函数,不能修改,而自定义函数是可以自行定义修改的。这些函数保存在plugins目录下,这些函数实现的功能跟html语法格式相同。

下面我给大家讲解一下smarty自定义函数里面的assign函数。这个函数是用于在模板被执行时为模板变量赋值。

语法:<{assign var="..." value="......"}> 这里我把smarty模板左面和右面的分隔符定义为了<{}>

参数:var: 声明变量名称 字符串

value:给该变量赋值 字符串

这是smarty已经写好的自定义函数,这些函数并不能满足我们的需求,这里我模仿assign函数,演示一个小例子实现自定义函数:包括a.html、b.php和init.inc.php三个文件

a.html

<{title num="3" content="aaa" size="7" color="green"}>

<{title num="5" content="bbb" size="2" color="red"}>
大家看到这里会不会感觉想以前学的html标签啊~~~~

init.inc.php

<?php

include("libs/Smarty.class.php");

$tpl = new Smarty();

$tpl->template_dir = 'templates';

$tpl->compile_dir = 'templates_c';

$tpl->left_delimiter = '<{';

$tpl->right_delimiter = '}>'; 这里我把smarty模板左面和右面的分隔符定义为了<{}>

?>

b.php

<?php

//本文件使用模版类

//首先包含该模板文件

include("init.inc.php");

//注册自定义函数

//register_function("smarty中的自定义函数名","php中自定义函数名")

$tpl->register_function("title","fun1");

//因为参数出现顺序无关,把参数保存到数组

function fun1($args){

$a="";

for($i=0;$i<$args["num"];$i++){

$a.="<font size=".$args["size"]." color=".$args['color'].">".$args["content"]."</font><br>";

}

return $a;

}

$tpl->display("a.html");

?>

上面演示的是自定义函数,下面我演示一下怎么定义一个块?所谓的块就是像html里面的双标记,有开始标记,也有结束标记,呈现一种块。

a.html

<{hello num="7" size="7" color="purple"}>1111<{/hello}>

<{say num=2 size="2" color="gray"}>hello world!!<{/say}>

b.php

<?php

//本文件使用模版类

//首先包含该模板文件

include("init.inc.php");

//注册一个块

$tpl->register_block("hello","fun2");

//定义块函数

function fun2($args,$content){

$a="";

for($i=0;$i<$args["num"];$i++){

$a.="<font size=".$args["size"]." color=".$args['color'].">".$content."</font><br>";

}

return $a;

}

$tpl->display("a.html");

?>

我们还可以在plugins目录下新建文件,在这里新建函数文件要注意几点,其它的就跟上面的差不多。

新建函数文件 world

例如:

function.assign_debug_info.php

function smarty_function_***(){}

步骤

第一步:plugins下新建文件function.world.php

第二步:打开文件

Function smarty_function_world($args,&$smarty){..}

新建块文件hello

block.hello.php

function smarty_block_hello(){}

第一步:plugins下新建块文件block.hello.php

第二步:打开文件

Function smarty_block_hello($args,$content,&$smarty){..}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐