A detailed description of writing the Smarty plug in to load data directly in the template

  • 2020-06-23 00:00:32
  • OfStack

When using smarty previously, the data is usually read from the php program side (usually from the database), and then the variable assign gives to the template can be used in the front end. This is not bad, but the php side of the code is a bit cumbersome to maintain when there is a lot of data, especially when there is a lot of template block data.

So I wrote a plug-in, combined with the previous crud class implementation in the front template can load some modular data.

<?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 data to a variable $params['assign'] , so that the front end can use the variable (for example, can be combined foreach The output 1 List, etc.) 
        $smarty->assign($params['assign'], $db->get_block_list(array($params['where']), $params['limit']));
    }
}
?>

In addition to saving a lot of maintenance, a significant benefit of writing a plug-in is the ability to format and filter queries against a database in the plug-in.
This loads the data in the front end like this:

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

Related articles: