search
HomeBackend DevelopmentPHP TutorialPHP template engine Smarty built-in function foreach, foreachelse usage analysis, smartyforeachelse_PHP tutorial

Usage 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

属性 类型 是否必须 缺省值 描述
from string Yes n/a 待循环数组的名称
item string Yes n/a 当前处理元素的变量名称
key string No n/a

当前处理元素的键名

name string No n/a 该循环的名称,用于访问该循环
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 ;
--
-- 转存表中的数据 `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)

<&#63;php
 define('ROOT_PATH', dirname(__FILE__)); //设置网站根目录
 require ROOT_PATH.'/libs/Smarty.class.php'; //加载 Smarty 模板引擎
 $_tpl = new Smarty(); //创建一个实例对象
 $_tpl->template_dir = ROOT_PATH.'/tpl/'; //重新指定模板目录
 $_tpl->compile_dir = ROOT_PATH.'./com/'; //重新指定编译目录
 $_tpl->left_delimiter = '<{'; //重新指定左定界符
 $_tpl->right_delimiter = '}>'; //重新指定右定界符
&#63;>

index.php (main file)

<&#63;php
 require 'init.inc.php'; //引入模板初始化文件
 global $_tpl;
 $_mysqli = new mysqli(); //创建一个 mysqli() 对象
 $_mysqli->connect('localhost','root','数据库密码','数据库名'); //连接数据库,请您自行设置
 $_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); //把数组分配到模板中
 $_tpl->display('index.tpl'); //引入模板
 $_mysqli->close(); //关闭数据库,释放资源
&#63;>

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 循环分配过来的数组有几行数据 -->
   <!-- 在此,我们做几个保留变量 $smarty.foreach 的操作 -->
   <!-- 当数据显示第一条的时候,第一行的表格背景为黄色,使用属性:first -->
   <!-- 当数据显示最后一条的时候,最后一行的表格背景为蓝色,使用属性:last -->
   <!-- 显示下分配过来的数组的总个数,使用属性: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 开始,每执行一次增加 1 -->
    <{foreach from=$row item="col" name="lsin"}> <!-- 这个foreach 循环数组内的内容,显示在表格的<td></td>标签里 -->
     <td><{$col}></td>
    <{/foreach}>
   </tr>
  <{foreachelse}> <!-- 如果分配过来的数组中没有数据,那么就执行下面的操作! -->
   <tr>
    <td>对不起!暂时没有数据。</td>
   </tr>
  <{/foreach}>
  <tr>
   <td colspan="4" align="center">分配数组的总记录数为:<{$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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1119977.htmlTechArticlePHP template engine Smarty built-in function foreach, foreachelse usage analysis, smartyforeachelse This article describes the built-in PHP template engine Smarty Function foreach, foreachelse usage. Share with everyone...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools