section是用来循环遍历的。只能循环索引数组(下标是连续的数字),对于关联数组是不能使用的。
常用的属性如下图:
其中name的值就是 对应 数组的 下标,具体来说,就是0,1,2,3....。也用于区别多个不同的section循环。
loop的值,其实就是要循环的次数,通常是一个整型,也可以使用数组作为它的值,如果是数组,则会使用count函数计算数组的长度,将结果作为循环的次数。
注意细节
1、loop 后面接的通常是 分配过来的数组,也可以直接写一个数字,如果接的是一个数组,则会计算其长度,作为其循环总次数。
2、而name相当于数组的索引值,即 0 ,1, 2,这样的索引值。也可用于区分多个不同的section循环。
3、和foreach类似,可以使用 index、iteration、first、last、total等属性,访问方式 $smarty.section.name.index,其中name就是name属性的值。
foreach和section的区别
foreach可以遍历任意数组,而section只能遍历索引连续的索引数组。
在一个循环中,遍历多个数组,使用section会方便一点。
section.php(后端):
<?php
include 'libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->template_dir = "templates";
$smarty->compile_dir = "templates_c";
$hero = array('id'=>1,'name'=>'黄药师','nickname'=>'东邪');
$smarty->assign('hero',$hero);
$user = array('张无忌','李寻欢','王语嫣','赵敏');
$user1 = array('张三','李四','王五','赵六');
$smarty->assign('user',$user);
$smarty->assign('user1',$user1);
$smarty->display('section.tpl');
section.tpl(前端视图):
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>section内置函数的使用</h2>
<ul>
{section name = 'idx' loop = 3} {* name的值"idx"可以随便写,idx本质上就是0,1,2,3....。name可以区别多个不同的section循环 *}
<li>{$hero[idx]}</li> {* 不能遍历循环关联数组 *}
{/section} {* section一定要有结束 *}
</ul>
<ul>
{section name = 'item' loop = $user max = 2}
<li>{$user[item]} --- {$user1[item]}</li> {* 同时遍历循环多个数组,section比foreach方便一点 *}
{/section}
</ul>
</body>
</html>