


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)
-- -- 表的結構 `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 ; -- -- 轉存表中的數(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__)); //設置網(wǎng)站根目錄 require ROOT_PATH.'/libs/Smarty.class.php'; //加載 Smarty 模板引擎 $_tpl = new Smarty(); //創(chuàng)建一個實例對象 $_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)建一個 mysqli() 對象 $_mysqli->connect('localhost','root','數(shù)據(jù)庫密碼','數(shù)據(jù)庫名'); //連接數(shù)據(jù)庫,請您自行設置 $_mysqli->set_charset('utf8'); //設置編碼 $_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(); //關閉數(shù)據(jù)庫,釋放資源 ?>
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"}> <!-- 這個foreach 循環(huán)分配過來的數(shù)組有幾行數(shù)據(jù) --> <!-- 在此,我們做幾個保留變量 $smarty.foreach 的操作 --> <!-- 當數(shù)據(jù)顯示第一條的時候,第一行的表格背景為黃色,使用屬性:first --> <!-- 當數(shù)據(jù)顯示最后一條的時候,最后一行的表格背景為藍色,使用屬性:last --> <!-- 顯示下分配過來的數(shù)組的總個數(shù),使用屬性:total --> <{if $smarty.foreach.ls.first}> <tr bgcolor="#FFFF00"> <!-- 第一行背景為黃色 --> <{elseif $smarty.foreach.ls.last}> <tr bgcolor="#0000FF"> <!-- 最后一行背景為藍色 --> <{else}> <tr> <{/if}> <td><{$smarty.foreach.ls.iteration}></td><!-- 注意:這里是保留變量 $smarty.foreach 的使用,iteration:總是從 1 開始,每執(zhí)行一次增加 1 --> <{foreach from=$row item="col" name="lsin"}> <!-- 這個foreach 循環(huán)數(shù)組內(nèi)的內(nèi)容,顯示在表格的<td></td>標簽里 --> <td><{$col}></td> <{/foreach}> </tr> <{foreachelse}> <!-- 如果分配過來的數(shù)組中沒有數(shù)據(jù),那么就執(zhí)行下面的操作! --> <tr> <td>對不起!暫時沒有數(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

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses
