【www.gdgbn.com--smarty模板】
{foreach},{foreachelse}用于像访问序数数组一样访问关联数组
Attribute Name属性名称
from:循环访问的数组
item:当前元素的变量名
key:当前键名的变量名
name:用于访问foreach属性的foreach循环的名称
{foreach from=$variable item = item key = key name=name}
{$variable|@count} //获取循环数组的长度
{$smarty.foreach.name.index} //获取当前循环数组元素的下标,以0开始
{$smarty.foreach.name.iteration} //获取循环次数,以1开始
{$smarty.foreach.name.first} //当为true时,标记循环第一次执行
{$smarty.foreach.name.last} //当为true时,标记循环最后一次执行
{$smarty.foreach.name.show} //当前是否显示
{$smarty.foreach.name.total} //循环次数
{/foreach}
Foreach源)(性能指标,迭代,第一个,最后,显示,整体。
$arr = array(1000, 1001, 1002);
$smarty->assign("myArray", $arr);
?>
Template to output $myArray in an un-ordered list
{foreach from=$myArray item=foo}
{$foo}
{/foreach}
The above example will output:
1000
1001
1002
Example 7-6. Demonstrates the item and key attributes
$arr = array(9 => "Tennis", 3 => "Swimming", 8 => "Coding");
$smarty->assign("myArray", $arr);
?>
Template to output $myArray as key/val pair, like PHP"s foreach.
{foreach from=$myArray key=k item=v}
{$k}: {$v}
{/foreach}
The above example will output:
9: Tennis
3: Swimming
8: Coding
Example 7-7. {foreach} with associative item attribute
$items_list = array(23 => array("no" => 2456, "label" => "Salad"),
96 => array("no" => 4889, "label" => "Cream")
);
$smarty->assign("items", $items_list);
?>
Template to output $items with $myId in the url
{foreach from=$items key=myId item=i}
{$i.no}: {$i.label}
{/foreach}
The above example will output:
2456: Salad
4889: Cream
Example 7-8. {foreach} with nested item and key
Assign an array to Smarty, the key contains the key for each looped value.
$smarty->assign("contacts", array(
array("phone" => "1",
"fax" => "2",
"cell" => "3"),
array("phone" => "555-4444",
"fax" => "555-3333",
"cell" => "760-1234")
));
?>
The template to output $contact.
{foreach name=outer item=contact from=$contacts}
{foreach key=key item=item from=$contact}
{$key}: {$item}
{/foreach}
{/foreach}
The above example will output:
phone: 1
fax: 2
cell: 3
phone: 555-4444
fax: 555-3333
cell: 760-1234