Home  >  Article  >  Backend Development  >  Detailed introduction to writing Smarty plug-ins to load data directly in templates_PHP tutorial

Detailed introduction to writing Smarty plug-ins to load data directly in templates_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:02:41820browse

When I used smarty before, I usually read data on the PHP terminal (usually from the database), and then assigned variables to the template before I could use this variable on the front end. This is not bad, but when there is a lot of data, it is a bit troublesome to maintain the code on the PHP side, especially when there is a lot of templated data.

So I wrote a plug-in, which can be combined with the previous crud class implementation to load some modularized data in the front-end template.

Copy code The code is as follows:

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

 * Name:     eval

 * Purpose:  evaluate a template variable as a template

 * @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 this variable (for example It can be combined with foreach to output a list, etc.) ]));
}
}
?>

Written as a plug-in, in addition to reducing a lot of maintenance, another significant benefit is that you can query in this plug-in Database operations perform unified formatting and filtering operations.

In this way, you can load data on the front end like this:
Copy the code The code is as follows:
{load_data assign="list" table="test" where="`id`<100" limit=10}
{foreach from=$list item=rec}
. ..
{/foreach}

http://www.bkjia.com/PHPjc/327902.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327902.htmlTechArticleWhen I used smarty before, I usually read the data in the php terminal (usually from the database), and then assigned it to Only template variables can be used in the front end. Isn’t that a bad thing...
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