Smarty 数组
在 Smarty 模板引擎中,数组是一种非常常见的数据结构,用于将多个相关的值传递到模板中。Smarty 支持处理 PHP 数组,并提供了一些特性来操作和显示这些数组数据。
传递数组到模板
要将数组传递到 Smarty 模板中,你可以使用 assign 方法。这里有一个示例:
// 创建一个一维数组 $user = array( "name" => "Jerry", "age" => 24 ); // 创建一个二维数组 $userList = array( array('name' => 'Jerry','age' => 24), array('name' => 'Tom','age' => 23), array('name' => 'Susan','age' => 22), ); // 将数组分配给模板 $smarty->assign('user', $user); $smarty->assign('userList', $userList);
在模板中遍历数组
访问一维数组
<html> <body> <h3>一维数组遍历演示:</h3> <p>用户名: {$user.name}</p> <p>年龄: {$user.age}</p> </body> </html>
访问二维数组
使用 foreach 方式
<h3>二维数组遍历演示(foreach):</h3> {foreach from=$userList item=user} <p> 用户名: {$user.name}, 年龄: {$user.age} </p> {/foreach}
使用 section 方法
<h3>二维数组遍历演示(section):</h3> {section name=item loop=$userList} <p> 用户名: {$userList[item].name}, 年龄: {$userList[item].age} </p> {/section}
使用 section 方式条件遍历
<h3>二维数组条件遍历演示(section):</h3> {section name=item loop=$userList start=1 max=2 step=1} <p> 用户名: {$userList[item].name}, 年龄: {$userList[item].age} </p> {/section}
在上述例子中,start=1 表示从第二个元素开始(索引从 0 开始)。max=2 表示循环最多 2 次。step=1 表示每次步进 1 个元素。
通过循环索引控制循环
{section name=item loop=$userList} <p> {if $smarty.section.item.index == 0} <strong>第一项:</strong> {/if} {if $smarty.section.item.last} <strong>最后一项.</strong> {/if} 用户名: {$userList[item].name}, 年龄: {$userList[item].age} </p> {/section}
Smarty 中统计数组长度
可以使用 count 函数,也可以使用 |@count 修饰符,在 section 循环中可以读取 loop 属性来获取数组长度
{count($userList)} {$userList|@count}
{section name=item loop=$userList} {$smarty.section.item.total} {/section}
Smarty 提供了丰富的功能来处理和显示数组数据,包括基本的 foreach 和 section 循环、内置函数 count、嵌套数组支持,以及自定义插件等。这些功能使得在模板中处理数组变得简单和高效。通过理解和利用这些功能,你可以轻松地在 Smarty 模板中实现复杂的数据展示和操作。