You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Blade的foreach循环中避免重复输出指定HTML标签

问题原因

你当前的实现依赖数组索引从0开始连续递增的规则,一旦$store_icon是关联数组、或者索引并非从0起步,$key < 1的判断就会失效,导致每次循环都满足条件输出提示标签。

最优解决方案

Blade 在@foreach循环中默认提供了内置的$loop变量,其中$loop->first属性会在第一次循环时返回true,后续循环返回false,完全不依赖数组本身的键值规则,兼容性最好:

@foreach ($store_icon as $key => $icon)
   @if ($loop->first)
       <p class="available-at">Also available at:</p>
   @endif
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach

其他可选方案

  • 确定$store_icon永远不为空时,可以直接把提示标签放到循环外部,不需要额外判断,性能最好:
<p class="available-at">Also available at:</p>
@foreach ($store_icon as $key => $icon)
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach
  • 如果你使用的是极旧版本不支持$loop变量,可以自定义标记变量控制输出:
@php $showAvailableTip = true; @endphp
@foreach ($store_icon as $key => $icon)
   @if ($showAvailableTip)
       <p class="available-at">Also available at:</p>
       @php $showAvailableTip = false; @endphp
   @endif
   <a href="{{ $store->product_url }}" target="_blank" style="margin-right: 2px"></a>
@endforeach

内容的提问来源于stack exchange,提问作者Catto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:54:01