電商分類頁:大分類 → 小分類 → 商品列表 三層結構,需在模板中逐層迴圈輸出。
$typeList = [
[
'typeName' => '手機通訊',
'shop' => [
['id'=>1, 'name'=>'iPhone 15', 'price'=>30000, 'num'=>10, 'img_url'=>'/img/iphone.jpg'],
['id'=>2, 'name'=>'Samsung S24', 'price'=>28000, 'num'=>5, 'img_url'=>'/img/samsung.jpg'],
]
],
[
'typeName' => '電腦辦公',
'shop' => [
['id'=>3, 'name'=>'MacBook Pro', 'price'=>60000, 'num'=>3, 'img_url'=>'/img/macbook.jpg'],
]
]
];
$smarty->assign('typeList', $typeList);
{section name=sec1 loop=$typeList}
<table class="category-header">
<tr>
<td><strong>{$typeList[sec1].typeName}</strong></td>
<td><a href="more.html">更多</a></td>
</tr>
</table>
<table class="product-grid">
<tr>
{section name=sec2 loop=$typeList[sec1].shop}
<td>
<a href="product.php?id={$typeList[sec1].shop[sec2].id}">
<img src="{$typeList[sec1].shop[sec2].img_url}" width="84" height="88">
</a>
<br>
<a href="product.php?id={$typeList[sec1].shop[sec2].id}">
{$typeList[sec1].shop[sec2].name}
</a>
<br>數量:{$typeList[sec1].shop[sec2].num}
<br>價格:{$typeList[sec1].shop[sec2].price} 元
</td>
{/section}
</tr>
</table>
{/section}
| 語法 | 說明 |
|---|---|
{section name=sec1 loop=$typeList} | 外層迴圈,索引變數 sec1 |
$typeList[sec1].shop | 存取外層當前項目的 shop 子陣列 |
{section name=sec2 loop=$typeList[sec1].shop} | 內層迴圈,索引變數 sec2,循環來源為動態子陣列 |
$typeList[sec1].shop[sec2].id | 雙重索引存取孫層屬性 |
{section name=sec1 loop=$typeList}
{$smarty.section.sec1.index} {* 0-based 索引 *}
{$smarty.section.sec1.iteration} {* 1-based 迴圈次數 *}
{$smarty.section.sec1.first} {* 是否第一筆 *}
{$smarty.section.sec1.last} {* 是否最後一筆 *}
{section name=sec2 loop=$typeList[sec1].shop}
{$smarty.section.sec2.index}
{/section}
{/section}
$typeList[$i]['shop'] 確實存在且為陣列。sec1/sec2)。section 直接不輸出,可搭配 {$typeList[sec1].shop|@count} 判斷顯示「無商品」。