How do I add foreach like features to smarty to automatically load data

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

In smarty, custom plug-ins are used to load data (see: detailed description of writing Smarty plug-ins to directly load data in the template). However, it is still not convenient to use.

Step 1: Add the _compile_tag function of Smarty_Compiler.class.php:

// Load the start tag of the data 
case 'load':
 $this->_push_tag('load');
 return $this->_complie_load_start($tag_args);
 break;
// The end tag for loading data 
case '/load':
 $this->_pop_tag('load');
 return "<?php endforeach; endif; unset(/$_from); ?>";
 break;

Step 2: Add 1 method:

/**
*  Load the data 
* @param $tag_args
*/
function _complie_load_start($tag_args)
{
 $key = substr(md5($tag_args), 8, 16);   // Generated by parameters 1 A special variable name 
 $attrs = $this->_parse_attrs($tag_args);
 // More processing can be added here 
 $class = (!isset($attrs['class']) || empty($attrs['class'])) ? 'cls_crud' : trim($attrs['class']);
 (!isset($attrs['table']) || empty($attrs['table'])) && exit('`table` is empty!');
 $db = $class::factory(array('table' => substr($attrs['table'], 1, -1)));
 // Define new variables 
 $this->_tpl_vars[$key] = $db->get_block_list(array(substr($attrs['where'], 1, -1)), $attrs['limit']);
 $tag_args = "from=/${$key} " . $tag_args;

 // call foreach The tag handler does the processing 
 return $this->_compile_foreach_start($tag_args);
}

This allows you to use the load tag in your template. For example:

{load table="test" where="`id`<100" limit=10 item=rec}
   ...
{/load}


Related articles: