{section loop = $varName[, start = $start, step = $step, max = $max, show = true]}
name: section的名称,不用加$
$loop: 要循环的变量,在程序中要使用assign对这个变量进行操作。
$start: 开始循环的下标,循环下标默认由0开始
$step: 每次循环时下标的增数
$max: 最大循环下标
$show: boolean类型,决定是否对这个块进行显示,默认为true
这里有个名词需要说明:
循环下标:实际它的英文名称为index,是索引的意思,这里我将它译成”下标”,主要是为了好理解。它表示在显示这个循环块时当前的循环索引,默认从0开始,受$start的影响,如果将$start设为5,它也将从5开始计数,在模板设计部分我们使用过它,这是当前 {section}的一个属性,调用方式为Smarty.section.sectionName.index,这里的sectionName指的是函数原型中的name属性。
{section}块具有的属性值,分别为:
1. index: 上边我们介绍的”循环下标”,默认为0
2. index_prev: 当前下标的前一个值,默认为-1
3. index_next: 当前下标的下一个值,默认为1
4. first: 是否为第一下循环
5. last: 是否为最后一个循环
6. iteration: 循环次数
7. rownum: 当前的行号,iteration的另一个别名
8. loop: 最后一个循环号,可用在section块后统计section的循环次数
9. total: 循环次数,可用在section块后统计循环次数
10. show: 在函数的声明中有它,用于判断section是否显示
————————————————————————————————–
{foreach} 用于像循环访问一个数字索引数组一样循环访问一个关联数组,与仅能访问数字索引数组的{section}不同,{foreach}的语法比 {section}的语法简单得多,但是作为一个折衷方案也仅能用于单个数组。每个{foreach}标记必须与关闭标记{/foreach}成对出现。
{foreach}循环也有自身属性的变量,可以通过{$smarty.foreach.name.property}访问,其中”name”是name属性。
{foreach}属性有index, iteration, first, last, show, total.
{foreach}的item属性是关联数组
<?php |
Template to output $items with $myId in the url
模板中,url通过$myId输出$items
<ul> {foreach from=$items key=myId item=i} <li><a href="item.php?id={$myId}">{$i.no}: {$i.label}</li> {/foreach} </ul> |
The above example will output:
上例将输出:
<ul> <li><a href="item.php?id=23">2456: Salad</li> <li><a href="item.php?id=96">4889: Cream</li> </ul> |
{foreach}使用嵌套的item和key
Assign an array to Smarty, the key contains the key for each looped value.
向Smarty设置一个数组,对于每个键名对应的每个循环值都包括键。
<?php |
The template to output $contact.
用于输出$contact的模板。
{foreach name=outer item=contact from=$contacts} <hr /> {foreach key=key item=item from=$contact} {$key}: {$item}<br /> {/foreach} {/foreach} |
The above example will output:
上例将输出:
<hr /> phone: 1<br /> fax: 2<br /> cell: 3<br /> <hr /> phone: 555-4444<br /> fax: 555-3333<br /> cell: 760-1234<br /> |
index示例
|
.iteration
iteration包含当前循环次数,与index不同,从1开始,每次循环增长1。
iteration和index示例
|
.first
first is TRUE if the current {foreach} iteration is the initial one.
first在当前{foreach}循环处于初始位置时值为TRUE。
first属性示例
|
.last
last is set to TRUE if the current {foreach} iteration is the final one.
last在当前{foreach}循环处于最终位置是值为TRUE。
last属性示例
|
.show
show is used as a parameter to {foreach}. show is a boolean value. If FALSE, the {foreach} will not be displayed. If there is a {foreachelse} present, that will be alternately displayed.
show是{foreach}的参数. show是一个布尔值。如果值为FALSE,{foreach}将不被显示。如果有对应的{foreachelse},将被显示。
.total
total contains the number of iterations that this {foreach} will loop. This can be used inside or after the {foreach}.
total包括{foreach}将循环的次数,既可以在{foreach}中使用,也可以在之后使用。
total属性示例
|
sdfsdfsd