【www.bbyears.com--smarty模板】
先来看section中的属性
name:(必选) 是section循环的名称只是标示循环唯一的名字没有特别意义,前面没有$符号;
loop: (必选)是在php声明中的变量名称,用来标示是循环哪一个数组(即要循环数组名)需要使用$;
start: (可选)循环执行的初始位置. 如果该值为负数,开始位置从数组的尾部算起. 例如:如果数组中有7个元素,指定start为-2,那么指向当前数组的索引为5. 非法值(超过了循环数组的下限)将被自动调整为最接近的合法值.
step: (可选)如其它语言的循环,是一个步长,如果为负数,则倒序循环;
max:(可选)循环的最大下标,如果是1则只循环1次,如果为2则循环2次;
show:(可选)默认为true即显示。如果设置了{sectionelse}。表示如果数组没有内容的时候显示这部分的内容;如果show为false则显示这部分。如果没有设置{sectionelse}则不输出该数组。
我们先看一个例子,这是经常会用到的
1、循环一个简单的一维数组:
php代码
代码如下
$data = array(1000,1001,1002);
$smarty->assign("custid",$data);
?>
htm模板
{{section name=loop loop=$custid step=1}}
seout="this.className="listout_box"">
{{$smarty.section.loop.rownum}}
城市
{{/section}}
2、不用assign数组直接在smarty中循环:
代码如下//特别地设置了start,step属性用来控制循环
//$smarty.section.section的名字.index是一个特殊变量,用来显示当前循环的位置
{section name=foo start=10 loop=20 step=2}
{$smarty.section.foo.index}
{/section}
{section name=bar loop=21 max=6 step=-2}
{$smarty.section.bar.index}
{/section}
//输出:
10 12 14 16 18
20 18 16 14 12 10
上面讲到的都是简单的,下面们来介绍关联数组
代码如下Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->1 $arr = array(
array("id"=>1,"title"=>"title1"),
array("id"=>2,"title"=>"title2"),
array("id"=>3,"title"=>"title3")
);
$smarty->assign("news",$arr);
在模板中显示过程如下
代码如下Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 {section name=sn loop=$news}
{if $smarty.section.sn.first}
{/if}
{$news[sn].id}
{$news[sn].title}
{if $smarty.section.sn.last}
{/if}
{sectionelse}
there is no news.
{/section}