| 特性 | {foreach} | {section} |
|---|---|---|
| 適用資料 | 關聯/數值陣列、物件 | 數值索引陣列為主 |
| 鍵值存取 | 直接 key, item | 透過索引 $arr[idx] |
| 屬性存取 | $item.prop | $arr[idx].prop |
| 迴圈屬性 | @index, @iteration, @first, @last, @total | .index, .iteration, .first, .last, .total |
| 巢狀支援 | 名稱隔離 name="outer" | 名稱隔離 name="outer" |
<table border="1">
{foreach key=k item=v from=$array1}
<tr>
<td>{$k}</td>
<td>{$v}</td>
<td>索引:{$v@index}</td>
<td>第幾次:{$v@iteration}</td>
<td>首項:{if $v@first}是{else}否{/if}</td>
<td>末項:{if $v@last}是{else}否{/if}</td>
</tr>
{/foreach}
</table>
<?php
require 'libs/Smarty.class.php';
$smarty = new Smarty();
$array1 = [1 => "Simon", 2 => "Elaine", 3 => "Susan"];
$smarty->assign("array1", $array1);
$smarty->display('test3.htm');
?>
<table border="1">
{section name=sec loop=$array1}
<tr>
<td>{$array1[sec]}</td>
<td>索引:{section name=sec print=.index}</td>
<td>首項:{if .first}是{else}否{/if}</td>
</tr>
{/section}
</table>
$array1 = [0 => "Simon", 1 => "Elaine", 2 => "Susan"]; // 關鍵:0 起始連續索引
$smarty->assign("array1", $array1);
$smarty->display('test10.htm');
{foreach $users as $user}
<div class="user {if $user@first}first{/if} {if $user@last}last{/if}">
<h3>{$user.name}</h3>
<span>{$user.email}</span>
<span>角色:{$user.role}</span>
</div>
{/foreach}
{foreach $categories as $cat}
<h2>{$cat.name}</h2>
<ul>
{foreach $cat.products as $prod name=prod_loop}
<li>{$prod.name} - {$prod.price}
{if $prod_loop@last}<span class="last">(本類最後)</span>{/if}
</li>
{/foreach}
</ul>
{/foreach}
{foreach $items as $item}
<li>{$item.name}</li>
{foreachelse}
<p>目前沒有任何項目</p>
{/foreach}
{foreach $items as $item}
{if $item.skip} {continue} {/if}
{if $item.stop} {break} {/if}
<li>{$item.name}</li>
{/foreach}
// 確保陣列索引適合 section
$array = array_values($assocArray); // 重設為 0 起始連續索引
// 大量資料分頁只傳當頁
$smarty->assign('items', array_slice($allItems, $offset, $pageSize));
$smarty->assign('pagination', $paginationData);
{foreach} 比 {section} 更靈活、效能略優{foreach} 是現代 Smarty 開發的主力迴圈語法,{section} 保留給相容舊模板使用。