| 特性 | foreach | section |
|---|---|---|
| 适用对象 | 关联数组、对象、遍历器 | 仅数字索引数组(列表) |
| 键名访问 | 直接 key 属性 | 需 $arr[section] 间接访问 |
| 嵌套支持 | 原生支持 name 区分层级 | 需手动管理 name 属性 |
| 性能 | 略优(直接迭代) | 略慢(索引计算) |
| 推荐度 | ⭐⭐⭐⭐⭐ 现代首选 | ⭐⭐ 兼容旧模板 |
{foreach $array as $key => $item}
{$key} => {$item}
{/foreach}
{* 带 name 属性,访问循环元数据 *}
{foreach $users as $user name=u}
{$smarty.foreach.u.index} {* 0-based *}
{$smarty.foreach.u.iteration} {* 1-based *}
{$smarty.foreach.u.first} {* bool *}
{$smarty.foreach.u.last} {* bool *}
{$smarty.foreach.u.show} {* bool 是否有数据 *}
{$smarty.foreach.u.total} {* 总数 *}
{$user.name}
{/foreach}
{section name=sec loop=$array}
{$array[sec]} {* 当前值 *}
{$smarty.section.sec.index} {* 0-based *}
{$smarty.section.sec.iteration} {* 1-based *}
{$smarty.section.sec.first}
{$smarty.section.sec.last}
{$smarty.section.sec.rownum} {* 迭代计数 *}
{$smarty.section.sec.loop} {* 总循环数 *}
{$smarty.section.sec.show}
{/section}
{* 步进、起始、最大 *}
{section name=sec loop=$array start=2 step=2 max=5}
{$array[sec]}
{/section}
<?php
// PHP 分配数据
$users = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@ex.com'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@ex.com'],
['id' => 3, 'name' => 'Carol', 'email' => 'carol@ex.com'],
];
$smarty->assign('users', $users);
<table border="1">
<tr><th>ID</th><th>姓名</th><th>邮箱</th></tr>
{foreach $users as $u}
<tr class="{cycle values='odd,even'}">
<td>{$u.id}</td>
<td>{$u.name}</td>
<td>{$u.email}</td>
</tr>
{foreachelse}
<tr><td colspan="3">暂无数据</td></tr>
{/foreach}
</table>
<table border="1">
<tr><th>ID</th><th>姓名</th><th>邮箱</th></tr>
{section name=u loop=$users}
<tr>
<td>{$users[u].id}</td>
<td>{$users[u].name}</td>
<td>{$users[u].email}</td>
</tr>
{sectionelse}
<tr><td colspan="3">暂无数据</td></tr>
{/section}
</table>
<?php
$categories = [
['name' => '电子', 'goods' => [['name'=>'手机'],['name'=>'耳机']]],
['name' => '服装', 'goods' => [['name'=>'T恤']]],
];
$smarty->assign('categories', $categories);
{foreach $categories as $cat}
<h3>{$cat.name}</h3>
<ul>
{foreach $cat.goods as $goods}
<li>{$goods.name}</li>
{/foreach}
</ul>
{/foreach}
$smarty->caching = true 缓存整个渲染结果foreach 拼接 HTML 片段,绕过模板引擎🔴
{foreach $arr as $v}中修改$v不影响原数组(值传递)
🔴section只能遍历数字索引数组,关联数组需先array_values()
🔴 嵌套循环未加name导致$smarty.foreach变量冲突
🔴 模板中大量逻辑判断,建议移至 PHP 端预处理标志位
掌握 foreach 核心语法与元数据访问,覆盖 99% 模板循环需求。