|
而樣版的寫法如下:
| 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 的應用範例。
|