(转)Smarty Foreach 使用说明

foreach 是除 section 之外处理循环的另一种方案(根据不同需要选择不同的方案)。 foreach 用于处理简单数组(数组中的元素的类型一致),它的格式比 section 简单许多,缺点是只能处理简单数组。
 
 

{foreach from=$custid item=curr_id} 
id: {$curr_id}<br> 
{/foreach} 

输出结果: 
id: 1000 
id: 1001 
id: 1002 
foreach 键的演示和嵌套的演示 
{* 
数组定义如下: 

$smarty->assign("contacts", array(array("phone" => "1", "fax" => "2", "cell" => "3"), 
array("phone" => "555-4444", "fax" => "555-3333", "cell" => "760-1234"))); 
*} 
{* 键就是数组的下标,请参看关于数组的解释 *} 
{foreach name=outer item=contact from=$contacts} 
{foreach key=key item=item from=$contact} 
{$key}: {$item}<br> 
{/foreach} 
{/foreach} 

输出结果: 
phone: 1 
fax: 2 
cell: 3 
phone: 555-4444 
fax: 555-3333 
cell: 760-1234 

.index 
index 包含当前数组索引,从"0"开始 
例如: 

<table> 
{foreach from=$items key=myId item=i name=foo} 
{if $smarty.foreach.foo.index % 5 == 0} {* $smarty.foreach.foo.index 对 5 求余 *} 
<tr><th>Title</th></tr> 
{/if} 
<tr><td>{$i.label}</td></tr> 
{/foreach} 
</table> 

.iteration 
iteration 包含当前循环的执行次数,总是从 1 开始,每执行一次自加 1。 
例如: 

{* 输出 0|1, 1|2, 2|3, ... 等等 *} 
{foreach from=$myArray item=i name=foo} 
{$smarty.foreach.foo.index}|{$smarty.foreach.foo.iteration}, 
{/foreach} 

.first 
当前 foreach 循环第一次执行时 first 被设置成 true。 
例如: 

{* 当循环第一次执行时显示 LATEST , o 否则显示 id *} 
<table> 
{foreach from=$items key=myId item=i name=foo} 
<tr> 
<td>{if $smarty.foreach.foo.first}LATEST{else}{$myId}{/if}</td> 
<td>{$i.label}</td> 
</tr> 
{/foreach} 
</table> 

.last 
当前 foreach 循环执行到最后一遍时 last 被设置成 true. 
例如: 

{* 在列表最后添加水平线 *} 
{foreach from=$items key=part_id item=prod name=products} 
<a href="#{$part_id}">{$prod}</a>{if $smarty.foreach.products.last}<hr>{else},{/if} 
{foreachelse} 
... content ... 
{/foreach} 

.total 
total 用于显示循环执行的次数,可以在循环中或循环执行后调用. 
例如: 

{* 在最后显示行数 *} 
{foreach from=$items key=part_id item=prod name=foo} 
{$prod.label}<hr/> 
{if $smarty.foreach.foo.last} 
<div >{$smarty.foreach.foo.total} items</div> 
{/if} 
{foreachelse} 
... something else ... 
{/foreach}