


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 ; -- -- 轉(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__)); //設置網(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

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
