萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Smarty 循环标签详解:foreach 与 section 的区别、嵌套、键值访问与性能对比

两大循环标签对比

特性foreachsection
适用对象关联数组、对象、遍历器仅数字索引数组(列表)
键名访问直接 key 属性需 $arr[section] 间接访问
嵌套支持原生支持 name 区分层级需手动管理 name 属性
性能略优(直接迭代)略慢(索引计算)
推荐度⭐⭐⭐⭐⭐ 现代首选⭐⭐ 兼容旧模板

foreach 完整语法

{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 完整语法

{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);

模板:foreach 版(推荐)

<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>

模板:section 版(仅演示)

<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}

性能优化建议

  • 大数据集(>1000 条)建议在 PHP 端分页,模板只渲染当前页
  • 避免在循环内调用复杂修饰器或函数,预先在 PHP 端计算好
  • 开启 $smarty->caching = true 缓存整个渲染结果
  • 若仅需简单列表,考虑直接在 PHP 用 foreach 拼接 HTML 片段,绕过模板引擎

常见坑

🔴 {foreach $arr as $v} 中修改 $v 不影响原数组(值传递)
🔴 section 只能遍历数字索引数组,关联数组需先 array_values()
🔴 嵌套循环未加 name 导致 $smarty.foreach 变量冲突
🔴 模板中大量逻辑判断,建议移至 PHP 端预处理标志位

掌握 foreach 核心语法与元数据访问,覆盖 99% 模板循环需求。

copyright © 萬盛學電腦網 all rights reserved