search
Homephp教程php手册编写Smarty插件在模板中直接加载数据的详细介绍

本篇文章是对编写Smarty插件在模板中直接加载数据进行了详细的分析介绍,需要的朋友参考下

之前使用smarty的时候,通常是在php程序端读取数据(一般从数据库),网站空间,然后assign给模板的变量,才可以在前端使用这个变量。这样不是不好,只是数据多的时候php端的代码维护起来有点麻烦,特别是当存在很多模板块化得数据时。

所以写了个插件,美国空间,结合之前的crud类实现在前端模板可以加载一些模块化得数据。

复制代码 代码如下:


/**
* Smarty plugin
* @package Smarty
* @subpackage plugins
*/
/**
* Smarty {load_data} function plugin
*
* Type: function

* Name: eval

* Purpose: evaluate a template variable as a template

* @link {eval}
* @param array
* @param Smarty
*/
function smarty_function_load_data($params, &$smarty)
{
$class = (!isset($params['class']) || empty($params['class'])) ? 'cls_crud' : trim($params['class']);
(!isset($params['table']) || empty($params['table'])) && exit('`table` is empty!');
$db = $class::factory(array('table' => $params['table']));
//var_dump($params);
if (!empty($params['assign'])) {
//把数据赋值给变量$params['assign'],这样前端就可以使用这个变量了(例如可以结合foreach输出一个列表等)
$smarty->assign($params['assign'], $db->get_block_list(array($params['where']), $params['limit']));
}
}
?>


写成插件除了可以减少很多维护之后,网站空间,还有一个显著的好处就是可以在这个插件中对查询数据库的操作进行统一的格式化和过滤操作。
这样在前端就可以这样加载数据了:

复制代码 代码如下:


{load_data assign="list" table="test" where="`id`{foreach from=$list item=rec}
...
{/foreach}

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor