萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Smarty foreach 循環控制變數完整指南:索引、計數、首尾判斷與次數限制

foreach 核心屬性 (`$smarty.foreach.name.property`)

屬性類型說明
indexint當前迭代索引 (從 0 開始)
iterationint當前迭代次數 (從 1 開始)
firstbool是否為第一次迭代
lastbool是否為最後一次迭代
showbool是否顯示內容 (受 `foreachelse` 影響)
totalint總迭代次數 (僅當陣列已知大小時)

基本語法

{foreach $items as $item name=foo}
    {$item@index}      {* 索引 *}
    {$item@iteration}  {* 次數 *}
    {$item@first}      {* 首項 *}
    {$item@last}       {* 尾項 *}
    {$item@total}      {* 總數 *}
{/foreach}

{* 等價長寫法 *}
{foreach from=$items item=item name=foo}
    ...
{/foreach}

實戰:限制顯示前 5 條

{foreach $VIDEO_INFO_LIST as $video name=vlist}
    {if $smarty.foreach.vlist.iteration <= 5}
        <li>{$video.title}</li>
    {/if}
{/foreach}

{* 或使用 index (從 0 開始) *}
{foreach $VIDEO_INFO_LIST as $video name=vlist}
    {if $smarty.foreach.vlist.index < 5}
        <li>{$video.title}</li>
    {/if}
{/foreach}

獲取陣列長度

{$VIDEO_INFO_LIST|@count}
{* 或在 foreach 內 *}
{$smarty.foreach.vlist.total}

巢狀迴圈存取外層屬性

{foreach $categories as $cat name=cat}
    {$smarty.foreach.cat.iteration}. {$cat.name}
    {foreach $cat.posts as $post name=post}
          - {$post.title} (外層索引: {$smarty.foreach.cat.index})
    {/foreach}
{/foreach}

foreachelse 空陣列處理

{foreach $emptyArray as $item}
    {$item}
{foreachelse}
    

暫無資料

{/foreach}

效能提示

  • 避免在模板中進行複雜邏輯,預先在 PHP 端處理好資料結構
  • 大量資料考慮分頁,模板僅渲染當頁資料
  • 啟用 Smarty 快取:`$smarty->caching = true;`
copyright © 萬盛學電腦網 all rights reserved