


PHP template engine Smarty built-in function foreach, foreachelse usage analysis, smartyforeachelse_PHP tutorial
Jul 12, 2016 am 08:54 AMUsage analysis of PHP template engine Smarty's built-in functions foreach and foreachelse, smartyforeachelse
This article describes the usage of PHP template engine Smarty's built-in functions foreach and foreachelse. Share it with everyone for your reference, the details are as follows:
In Smarty templates, you can use foreach to repeat a block. In the template, an array needs to be allocated from PHP. This array can be a multidimensional array. The {foreach} tag in Smarty is the same as the foreach in PHP, except that one of them is used in the template file and the other is used in the PHP script. Therefore, the syntax will be different. However, they all do the same thing, which is to iterate over the contents of an array. There is also a {foreachelse} tag opposite to the {foreach} tag. The function of the {foreachelse} tag is: if the array is empty, then the content in the tag is executed. {foreach} and {/foreach} must appear in pairs in the template. It has four parameters, of which two parameters from and item are necessary. Please see the list below for its parameters:
property | Type | Is it necessary | Default value | Description | |||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from | string | Yes | n/a | Name of the array to be looped | |||||||||||||||||||||||||
item | string | Yes | n/a | Variable name of the currently processed element | |||||||||||||||||||||||||
key | string | No | n/a |
Key name of the currently processed element
|
|||||||||||||||||||||||||
name | string | No | n/a | The name of the loop, used to access the loop |
We use an example to demonstrate the use of {foreach} and {foreachelse} in Smarty.
Example idea: retrieve the content from the database, assign it to an array variable $_html, then assign this array variable to the template, and then traverse the array in the template
test.sql (SQL data used)
-- -- 表的結(jié)構(gòu) `user` -- CREATE TABLE IF NOT EXISTS `user` ( `id` mediumint(8) unsigned NOT NULL auto_increment, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `addTime` datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; -- -- 轉(zhuǎn)存表中的數(shù)據(jù) `user` -- INSERT INTO `user` (`id`, `username`, `email`, `addTime`) VALUES (1, '蒼井空', 'canjingkong@sina.com.cn', '2011-10-24 00:00:00'), (2, '櫻木花道', 'ymhd@163.com', '2011-10-24 00:00:00'), (3, '赤木晴子', 'chimiqingzi@yahoo.com,cn', '2011-10-24 00:00:00'), (4, '流川楓', 'lcfeng@sina.com', '0000-00-00 00:00:00'), (5, '蠟筆小新', 'labixiaoxin@sina.com', '2011-10-24 00:00:00'), (6, '金剛葫蘆娃', 'jghlw@sina.com', '2011-10-24 00:00:00');
init.inc.php (template initialization file)
<?php define('ROOT_PATH', dirname(__FILE__)); //設(shè)置網(wǎng)站根目錄 require ROOT_PATH.'/libs/Smarty.class.php'; //加載 Smarty 模板引擎 $_tpl = new Smarty(); //創(chuàng)建一個(gè)實(shí)例對(duì)象 $_tpl->template_dir = ROOT_PATH.'/tpl/'; //重新指定模板目錄 $_tpl->compile_dir = ROOT_PATH.'./com/'; //重新指定編譯目錄 $_tpl->left_delimiter = '<{'; //重新指定左定界符 $_tpl->right_delimiter = '}>'; //重新指定右定界符 ?>
index.php (main file)
<?php require 'init.inc.php'; //引入模板初始化文件 global $_tpl; $_mysqli = new mysqli(); //創(chuàng)建一個(gè) mysqli() 對(duì)象 $_mysqli->connect('localhost','root','數(shù)據(jù)庫(kù)密碼','數(shù)據(jù)庫(kù)名'); //連接數(shù)據(jù)庫(kù),請(qǐng)您自行設(shè)置 $_mysqli->set_charset('utf8'); //設(shè)置編碼 $_result = $_mysqli->query("select username,email,addTime from user order by id asc"); $_html = array(); while (!!$_row=$_result->fetch_assoc()) { $_html[] = $_row; } $_tpl->assign('data',$_html); //把數(shù)組分配到模板中 $_tpl->display('index.tpl'); //引入模板 $_mysqli->close(); //關(guān)閉數(shù)據(jù)庫(kù),釋放資源 ?>
tpl/index.tpl (template file of the main file index.php)
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>foreach,foreachelse</title> </head> <body> <table align="center" border="1" width="800"> <{foreach from=$data item="row" name="ls"}> <!-- 這個(gè)foreach 循環(huán)分配過(guò)來(lái)的數(shù)組有幾行數(shù)據(jù) --> <!-- 在此,我們做幾個(gè)保留變量 $smarty.foreach 的操作 --> <!-- 當(dāng)數(shù)據(jù)顯示第一條的時(shí)候,第一行的表格背景為黃色,使用屬性:first --> <!-- 當(dāng)數(shù)據(jù)顯示最后一條的時(shí)候,最后一行的表格背景為藍(lán)色,使用屬性:last --> <!-- 顯示下分配過(guò)來(lái)的數(shù)組的總個(gè)數(shù),使用屬性:total --> <{if $smarty.foreach.ls.first}> <tr bgcolor="#FFFF00"> <!-- 第一行背景為黃色 --> <{elseif $smarty.foreach.ls.last}> <tr bgcolor="#0000FF"> <!-- 最后一行背景為藍(lán)色 --> <{else}> <tr> <{/if}> <td><{$smarty.foreach.ls.iteration}></td><!-- 注意:這里是保留變量 $smarty.foreach 的使用,iteration:總是從 1 開(kāi)始,每執(zhí)行一次增加 1 --> <{foreach from=$row item="col" name="lsin"}> <!-- 這個(gè)foreach 循環(huán)數(shù)組內(nèi)的內(nèi)容,顯示在表格的<td></td>標(biāo)簽里 --> <td><{$col}></td> <{/foreach}> </tr> <{foreachelse}> <!-- 如果分配過(guò)來(lái)的數(shù)組中沒(méi)有數(shù)據(jù),那么就執(zhí)行下面的操作! --> <tr> <td>對(duì)不起!暫時(shí)沒(méi)有數(shù)據(jù)。</td> </tr> <{/foreach}> <tr> <td colspan="4" align="center">分配數(shù)組的總記錄數(shù)為:<{$smarty.foreach.ls.total}>條</td> </tr> </table> </body> </html>
Execution result:
Finally, the array $_html passed in the main file index.php is a two-dimensional array. The use of reserved variables $smarty.foreach is based on the name attribute in the {foreach} tag. The reserved variable attributes used are: first (first record), last (last record), iteration (always starts from 1, Increase by 1 for each execution), total (used to display the number of loop executions)
Readers who are interested in more PHP-related content can check out the special topics of this site: "Basic Tutorial for Getting Started with Smarty Templates", "Summary of PHP Template Technology", "Summary of PHP Database Operation Skills Based on PDO", "PHP Operations and Operators" Usage summary", "PHP network programming skills summary", "PHP basic syntax introductory tutorial", "php object-oriented programming introductory tutorial", "php string (string) usage summary", "php mysql database operation introductory tutorial" and "Summary of Common Database Operation Skills in PHP"
I hope this article will be helpful to everyone’s PHP program design based on smarty templates.
Articles you may be interested in:
- Detailed explanation of the built-in functions of PHP template engine Smarty
- Detailed explanation of the usage of the built-in variable mediator of PHP template engine Smarty
- PHP Usage of custom variable mediator in template engine Smarty
- Analysis of usage of reserved variables in PHP template engine Smarty
- Example of how to use the configuration file of PHP template engine Smarty in template variables
- Examples of how to use variables in PHP template engine Smarty
- How smarty template engine gets data from php
- ThinkPHP How to use smarty template engine
- In PHP template Detailed explanation of the random number generation method and math function of engine smarty
- Summary of cache usage of PHP template engine Smarty
- 6 tips of php smarty template engine
- [PHP] template An in-depth and simple introduction to the engine Smarty
- Detailed explanation of the usage of the built-in functions section and sectionelse of the PHP template engine Smarty

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f
