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

yipeiwu_com5年前PHP代码库
在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;

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

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

{load table="test" where="`id`<100" limit=10 item=rec}
   ...
{/load}

相关文章

用PHP代码在网页上生成图片

用PHP代码在网页上生成图片

代码很简单,这里就不多废话了, <?php /** * Created by PhpStorm. * User: Administrator * Date: 2...

PHP执行zip与rar解压缩方法实现代码

Zip:PclZip http://www.phpconcept.net/pclzip/index.en.php Rar:PECL rar http://pecl.php.net/pac...

PHP与SQL注入攻击防范小技巧

下面来谈谈SQL注入攻击是如何实现的,又如何防范。  看这个例子: 复制代码 代码如下: // supposed input $name = "ilia'; DELETE FROM us...

php判断当前用户已在别处登录的方法

本文实例讲述了php判断当前用户已在别处登录的方法。分享给大家供大家参考。具体分析如下: 主要思路如下: 1.登录时,将用户的SessionID记录下来 2.验证登录时,将记录的该用户S...

PHP new static 和 new self详解

PHP new static 和 new self详解

最近在一个视频的评论被问到一个小问题:这里选择用static 而不是self有特殊的考虑么?或者我们可以这样转换一下问题: PHP 的 new static 和 new self 具体有...