如何在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
相关产品推荐
相关产品推荐

