foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案)。 foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组。
foreach 必须和 /foreach 成对使用,且必须指定 from 和 item 属性。
将 from 属性指定的数组中的数据遍历处理到 item 属性指定的变量中。
参考 foreach (array_expression as $key => $value)
from <=> array_expression;item <=> $value;key <=> $key。
name 属性可以任意指定(字母、数字和下划线的组合)。
foreach 可以嵌套,但必须保证嵌套中的 foreach 名称唯一。
from 属性(通常是数组)决定循环的次数。
foreachelse 语句在 from 属性没有值的时候被执行。(from 属性所指定的值为空时,可用 foreachelse 语句指定——否则-干什么)
foreach 循环有自己的变量名,使用该变量名可以访问该循环. 使用方法为 {$smarty.foreach.foreachname.varname},其中 foreachname 即在 foreach 中指定的 name 属性。
foreach 演示
{* 该例将输出数组 $custid 中的所有元素的值 *}
1 { foreach from = $custid item = curr_id}
2 id : { $curr_id } < br >
3 { / foreach }
输出结果:
id: 1000
id: 1001
id: 1002
foreach 键的演示和嵌套的演示
{*
数组定义如下:
1 $smarty -> assign( " contacts " , array ( array ( " phone " => " 1 " , " fax " => " 2 " , " cell " => " 3 " ) ,
2 array ( " phone " => " 555-4444 " , " fax " => " 555-3333 " , " cell " => " 760-1234 " )));
3 * }
4 { * 键就是数组的下标,请参看关于数组的解释 * }
5
6 { foreach name = outer item = contact from = $contacts }
7 { foreach key = key item = item from = $contact }
8 { $key } : { $item } < br >
9 { / foreach }
10 { / foreach }
11
输出结果:
phone: 1
fax: 2
cell: 3
phone: 555-4444
fax: 555-3333
cell: 760-1234
.index
index 包含当前数组索引,从"0"开始
例如:
1 < table >
2 { foreach from = $items key = myId item = i name = foo}
3 { if $smarty . foreach . foo . index % 5 == 0 } { * $smarty . foreach . foo . index 对 5 求余 * }
4 < tr >< th > Title </ th ></ tr >
5 { / if }
6 < tr >< td > { $i . label} </ td ></ tr >
7 { / foreach }
8 </ table >
.iteration
iteration 包含当前循环的执行次数,总是从 1 开始,每执行一次自加 1。
例如:
1 { * 输出 0 | 1 , 1 | 2 , 2 | 3 , ... 等等 * }
2 { foreach from = $myArray item = i name = foo}
3 { $smarty . foreach . foo . index} | { $smarty . foreach . foo . iteration} ,
4 { / foreach }
.first
当前 foreach 循环第一次执行时 first 被设置成 true。
例如:
1 { * 当循环第一次执行时显示 LATEST , o 否则显示 id * }
2 < table >
3 { foreach from = $items key = myId item = i name = foo}
4 < tr >
5 < td > { if $smarty . foreach . foo . first}LATEST{ else }{ $myId }{ / if } </ td >
6 < td > { $i . label} </ td >
7 </ tr >
8 { / foreach }
9 </ table >
.last
当前 foreach 循环执行到最后一遍时 last 被设置成 true.
例如:
1 { * 在列表最后添加水平线 * }
2 { foreach from = $items key = part_id item = prod name = products}
3 < a href = " #{ $part_id } " > { $prod } </ a > { if $smarty . foreach . products . last} < hr > { else } , { / if }
4 {foreachelse}
5 ... content ...
6 { / foreach }
.total
total 用于显示循环执行的次数,可以在循环中或循环执行后调用.
例如:
1 { * 在最后显示行数 * }
2 { foreach from = $items key = part_id item = prod name = foo}
3 { $prod . label} < hr />
4 { if $smarty . foreach . foo . last}
5 < div id = " total " > { $smarty . foreach . foo . total} items </ div >
6 { / if }
7 {foreachelse}
8 ... something else ...
9
10 { / foreach }
11