background image

PHP 教程

smarty 中增加类似 foreach 的功能自动加载数据

smarty 中使用自定义插件来加载数据(见:编写 Smarty 插件在模板中直接加载数据的详

细介绍),在使用的时候还是感觉不够方便,灵机一动就想写成类似

foreach

那种标签:

 
第一步:在

Smarty_Compiler.

class

.php 的_compile_tag 函数中增加:

代码如下

:

 

//加载数据的开始标签
case

 'load':

$this

->_push_tag('load');

return

 

$this

->_complie_load_start(

$tag_args

);

break

;

//加载数据的结束标签
case

 '/load':

$this

->_pop_tag('load');

return

 "<?php endforeach; endif; unset(/$_from); ?>";

break

;

 
第二步:增加一个方法:
代码如下

:

 

/**
* 加载数据
* @param $tag_args
*/
function

 _complie_load_start(

$tag_args

)

{

$key

 = 

substr

(md5(

$tag_args

), 8, 16); 

//根据参数生成一个特殊的变量名

$attrs

 = 

$this

->_parse_attrs(

$tag_args

);

//这里可以增加更多的处理

$class

 = (!isset(

$attrs

['class']) || 

empty

(

$attrs

['class'])) ? 'cls_crud' : trim(

$attrs

['class']);

(!isset(

$attrs

['table']) || 

empty

(

$attrs

['table'])) && 

exit

('`table` is empty!');

$db

 = 

$class

::factory(

array

('table' => 

substr

(

$attrs

['table'], 1, -1)));

//定义新变量

$this

->_tpl_vars[

$key

] = 

$db

->get_block_list(

array

(

substr

(

$attrs

['where'], 1, -1)), 

$attrs

['limit']);

$tag_args

 = "from=/${$key} " . 

$tag_args

;