Home  >  Article  >  Backend Development  >  How to add a foreach-like function to automatically load data in smarty_PHP tutorial

How to add a foreach-like function to automatically load data in smarty_PHP tutorial

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

Use a custom plug-in to load data in smarty (see: Detailed introduction to writing Smarty plug-ins to load data directly in templates). It still feels inconvenient when using it. I had an idea and wanted to write a tag like foreach:

Step one: Add in the _compile_tag function of Smarty_Compiler.class.php:

Copy the code The code is as follows:

//Start tag of loading data
case 'load':
$this->_push_tag('load');
return $this->_complie_load_start($ tag_args);
break;
//End tag of loading data
case '/load':
$this->_pop_tag('load');
return "";
break;

Step 2: Add a method:
Copy code The code is as follows:

/**
* Load data
* @param $tag_args
*/
function _complie_load_start($tag_args)
{
$key = substr(md5($tag_args), 8, 16); //Generate a special variable name based on the parameters
$attrs = $this->_parse_attrs($tag_args);
//Here More processing can be added
$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 the foreach tag processing function for processing
return $this->_compile_foreach_start($tag_args);
}

In this way, you can use the load tag in the template. Usage example:
Copy code The code is as follows:

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327901.htmlTechArticleUse custom plug-ins in smarty to load data (see: details on writing Smarty plug-ins to load data directly in templates Introduction), I still felt that it was not convenient enough when using it, so I had an idea...
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