How to add a foreach-like feature to the smarty automatically load data _php tips

Source: Internet
Author: User
Use custom Plug-ins in Smarty to load data (see: Write a detailed description of the Smarty plug-in loading data directly in the template), or feel inconvenient when it is used, and brainwave want to write a label like foreach:

Step One: Add in the _compile_tag function of Smarty_Compiler.class.php:
Copy Code code as follows:

Start tag for loading data
Case ' Load ':
$this->_push_tag (' Load ');
return $this->_complie_load_start ($tag _args);
Break
Load end tag of data
Case '/load ':
$this->_pop_tag (' Load ');
return "<?php Endforeach; endif Unset (/$_from);?> ";
Break

Step Two: Add a method:
Copy Code code 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 from a parameter
$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 variable
$this->_tpl_vars[$key] = $db->get_block_list (Array (substr ($attrs [' where '], 1,-1)), $attrs [' limit ']);
$tag _args = "from=/${$key}". $tag _args;

Invoke the foreach tag handler function for processing
return $this->_compile_foreach_start ($tag _args);
}

This allows you to use the load tag in the template. Usage for example:
Copy Code code as follows:

{load table= ' test ' where= ' id ' <100 ' limit=10 Item=rec}
...
{/load}

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.