Detailed introduction to writing Smarty Plug-ins to load data directly in the template

Source: Internet
Author: User
Tags foreach eval

Before using smarty, you usually read the data from the PHP program (typically from the database) and then assign the variables to the template before you can use the variable on the front end. This is not bad, but the data when the PHP side of the code to maintain a bit of trouble, especially when there are a lot of template block data.

So write a plugin, combining the previous CRUD classes implemented in the front-end template can load some modular data.

Copy Code code as follows:


<?php


/**


* Smarty Plugin


* @package Smarty


* @subpackage Plugins


*/


/**


* Smarty {load_data} function plugin


*


* type:function<br>


* name:eval<br>


* Purpose:evaluate A template variable as a template<br>


* @link http://smarty.php.net/manual/en/language.function.eval.php {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 '])) {


//Assign the data to the variable $params[' assign ' so that the front end can use the variable (for example, you can output a list with foreach, etc.)


$smarty->assign ($params [' Assign '], $db->get_block_list (Array ($params [' where ']), $params [' limit ']);


}


}


?>


As a plug-in, in addition to reducing a lot of maintenance, there is a significant advantage is that the query database in this plug-in to the operation of a unified format and filtering operations.
This allows the data to be loaded on the front end:

Copy Code code as follows:


{load_data assign= ' list ' table= ' test ' where= ' id ' <100 ' limit=10}
{foreach from= $list Item=rec}
...
{/foreach}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.