Smarty 选择语句
Smarty include 

Smarty 循环语句

Smarty 是一个 PHP  模板引擎,它允许开发者将 PHP 逻辑与 HTML 内容分离,从而创建动态网页。在 Smarty 中,可以使用foreach 和 section 来进行循环操作。下面分别介绍 foreach 和 section 的基本用法。


foreach 的用法

基本语法

{foreach from=$array item=item name=loop}
    {$item}
{/foreach}

参数说明

  • from:要循环的数组或对象。

  • item:每次循环时当前元素的变量名。

  • name:循环的名称(可选)。

使用示例

假设你有一个包含多个用户的数组,你可以用 foreach 循环来显示这些用户的名字:

// 创建一个二维数组
$userList = array(
    array('name' => 'Jerry','age' => 24),
    array('name' => 'Tom','age' => 23),
    array('name' => 'Susan','age' => 22),
);
 
// 将数组分配给模板
$smarty->assign('userList', $userList);

Smarty模板

<h3>foreach循环演示:</h3>
{foreach from=$userList item=user}
    <p>
        用户名: {$user.name}, 年龄: {$user.age} 
    </p>
{/foreach}

其他选项

你还可以使用 key 参数来获取数组的键:

{foreach from=$userList item=user}
    <p>Index: {$index}, 用户名: {$user.name}, 年龄: {$user.age}</p>
{/foreach}

iteration属性

如果需要获取当前循环的迭代次数或其他循环相关信息,可以使用 iteration 属性:

{foreach from=$userList item=user name=users}
    <p>Iteration: {$smarty.foreach.users.iteration}, 用户名: {$user.name}, 年龄: {$user.age}</p>
{/foreach}

这些属性包括:

  • iteration:当前的迭代次数。

  • index:当前循环的索引(从 0 开始)。


section的用法

基本语法

{section name=sectionName loop=totalLoops start=startValue step=stepValue show=true}
    //循环逻辑
{/section}

参数说明

  • name:定义循环的名字,这样可以在循环体内使用 sectionName.index、sectionName.first 等变量。

  • loop:指定循环的总次数。

  • start:指定循环开始的值,默认是 0。

  • step:指定每次迭代的增量,默认是 1。

  • show:是否显示循环的实际值,默认为 true。

使用示例

<h3>section循环演示:</h3>
{section name=item loop=$userList}
    <p>
        用户名: {$userList[item].name}, 年龄: {$userList[item].age} 
    </p>
{/section}

section标签

  • $smarty.section.[name].index:当前迭代的索引(从0开始)。

  • $smarty.section.[name].iteration:当前迭代的次数(从1开始)。

  • $smarty.section.[name].total:循环的总次数。

  • $smarty.section.[name].first:如果是第一次迭代,则为true。

  • $smarty.section.[name].last:如果是最后一次迭代,则为true。


foreach 与 section 区别总结

  • section 用于生成固定次数的迭代,不依赖于外部数据源。

  • foreach 用于遍历和输出数组或对象中的元素,依赖于外部数据源。

  • section 提供了循环状态的内置变量,而 foreach 提供了当前元素和索引的访问。

  • foreach 更适合处理复杂的数据结构和嵌套循环