Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-13 11:44:42
Original
703 people have browsed it

在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 "";
 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;

 //调用foreach标签处理函数进行处理
 return $this->_compile_foreach_start($tag_args);
}


这样就可以在模板中使用load这个标签了。用法例如:

复制代码 代码如下:


{load table="test" where="`id`   ...
{/load}


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!