本篇文章是对编写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}

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

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
