如何在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 "";
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}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
