我在 Blade 模板中有一个 @foreach 循环,需要对集合中的第一项应用特殊格式。如何添加条件来检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
Laravel 在
$loop
循环中提供了 foreach
变量。
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
苏荷区,
最快的方法是将当前元素与数组中的第一个元素进行比较:
@foreach($items as $item)
@if ($item == reset($items )) First Item: @endif
<h4>{{ $item->program_name }}</h4>
@endforeach
否则,如果它不是关联数组,您可以按照上面的答案检查索引值 - 但如果数组是关联数组,则不起作用。
取键值即可
@foreach($items as $index => $item)
@if($index == 0)
...
@endif
<h4>{{ $item->program_name }}</h4>
@endforeach
从 Laravel 7.25 开始,Blade 现在包含一个新的 @once 组件,所以你可以这样做:
@foreach($items as $item)
@once
<h4>{{ $item->program_name }}</h4> // Displayed only once
@endonce
// ... rest of looped output
@endforeach
Laravel 7.* 提供了
first()
辅助函数。
{{ $items->first()->program_name }}
*请注意,我不确定这是何时引入的。因此,它可能不适用于早期版本。
这里仅在文档中简要提及。
Liam Wiltshire 答案的主要问题是性能,因为:
reset($items) 在每个循环中一次又一次地倒回 $items 集合的指针...总是得到相同的结果。
$item 和 reset($item) 的结果都是对象,因此 $item == reset($items) 需要对其属性进行完整比较...需要更多的处理器时间。
一种更高效、更优雅的方法 - 正如 Shannon 建议的那样 - 是使用 Blade 的 $loop 变量:
@foreach($items as $item)
@if ($loop->first) First Item: @endif
<h4>{{ $item->program_name }}</h4>
@endforeach
如果您想对第一个元素应用特殊格式,那么也许您可以执行类似的操作(使用三元条件运算符
?: ):
@foreach($items as $item)
<h4 {!! $loop->first ? 'class="special"': '' !!}>{{ $item->program_name }}</h4>
@endforeach
请注意使用
{!!
和
!!}
标签而不是
{{
}}
表示法,以避免对special 字符串周围的双引号进行 html 编码。 问候。
@break
或
@foreach
中使用
@if
。参见示例:
@foreach($media as $m)
@if ($m->title == $loc->title) :
<img class="card-img-top img-fluid" src="images/{{ $m->img }}">
@break
@endif
@endforeach
collect($users )->first();
@foreach($items as $item)
@if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
@else
<h5>{{$item->program_name}}</h5>
@endif
@endforeach