> "data4-2", "index3" => "data4-3"),
array("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3"));
$tpl->assign("array2", $array2);
$tpl->display("test2.htm");
?>
而模版的写法如下:
templates/test2.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>测试重复区块</title>
</head>
<body>
<pre>
利用 foreach 来呈现 array1
<{foreach item=item1 from=$array1}>
<{$item1}>
<{/foreach}>
利用 section 来呈现 array1
<{section name=sec1 loop=$array1}>
<{$array1[sec1]}>
<{/section}>
利用 foreach 来呈现 array2
<{foreach item=index2 from=$array2}>
<{foreach key=key2 item=item2 from=$index2}>
<{$key2}>: <{$item2}>
<{/foreach}>
<{/foreach}>
利用 section 来呈现 array1
<{section name=sec2 loop=$array2}>
index1: <{$array2[sec2].index1}>
index2: <{$array2[sec2].index2}>
index3: <{$array2[sec2].index3}>
<{/section}>
</pre>
</body>
</html>
执行上例后,我们发现不管是 foreach 或 section 两个执行结果是一样的。那么两者到底有何不同呢?
第一个差别很明显,就是foreach 要以巢状处理的方式来呈现我们所 assign 的两层数组变量,而 section 则以「主数组[循环名称].子数组索引」即可将整个数组呈现出来。由此可知, Smarty 在模版中的 foreach 和 PHP 中的 foreach 是一样的;而 section 则是 Smarty 为了处理如上列的数组变量所发展出来的叙述。当然 section 的功能还不只如此,除了下一节所谈到的巢状资料呈现外,官方手册中也提供了好几个 section 的应用范例。
不过要注意的是,丢给 section 的数组索引必须是从 0 开始的正整数,即 0, 1, 2, 3, ...。如果您的数组索引不是从 0 开始的正整数,那
array("index1" => "data5-1", "index2" => "data5-2", "index3" => "data5-3"));
$tpl->assign("array2", $array2);
$tpl->display("test2.htm");
?>
而模版的写法如下:
templates/test2.htm:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=big5">
<title>测试重复区块</title>
</head>
<body>
<pre>
利用 foreach 来呈现 array1
<{foreach item=item1 from=$array1}>
<{$item1}>
<{/foreach}>
利用 section 来呈现 array1
<{section name=sec1 loop=$array1}>
<{$array1[sec1]}>
<{/section}>
利用 foreach 来呈现 array2
<{foreach item=index2 from=$array2}>
<{foreach key=key2 item=item2 from=$index2}>
<{$key2}>: <{$item2}>
<{/foreach}>
<{/foreach}>
利用 section 来呈现 array1
<{section name=sec2 loop=$array2}>
index1: <{$array2[sec2].index1}>
index2: <{$array2[sec2].index2}>
index3: <{$array2[sec2].index3}>
<{/section}>
</pre>
</body>
</html>
执行上例后,我们发现不管是 foreach 或 section 两个执行结果是一样的。那么两者到底有何不同呢?
第一个差别很明显,就是foreach 要以巢状处理的方式来呈现我们所 assign 的两层数组变量,而 section 则以「主数组[循环名称].子数组索引」即可将整个数组呈现出来。由此可知, Smarty 在模版中的 foreach 和 PHP 中的 foreach 是一样的;而 section 则是 Smarty 为了处理如上列的数组变量所发展出来的叙述。当然 section 的功能还不只如此,除了下一节所谈到的巢状资料呈现外,官方手册中也提供了好几个 section 的应用范例。
不过要注意的是,丢给 section 的数组索引必须是从 0 开始的正整数,即 0, 1, 2, 3, ...。如果您的数组索引不是从 0 开始的正整数,那
| 对此文章发表了评论 |
