我在Blade模板中有一个@foreach循环,需要对集合中的第一个项应用特殊格式。如何添加条件以检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
Laravel 5.3在foreach
循环中提供一个$loop
变量。
@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
文档:https://laravel.com/docs/5.3/blade#the-循环变量
SoHo,
最快的方法是将当前元素与数组中的第一个元素进行比较:
@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答案的主要问题是性能,因为:
-
重置($items)在每个循环中一次又一次地倒带$items集合的指针。。。结果总是一样的。
-
$item和重置结果($item)都是对象,因此$item==重置($items)
一种更有效、更优雅的方法是使用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
请注意使用{!!
和!!}
标记而不是{{
}}
表示法,以避免对特殊字符串周围的双引号进行html编码。
谨致问候。
如果只需要第一个元素,则可以在@foreach
或@if
中使用@break
。参见示例:
@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();
要在Laravel中获取集合的第一个元素,可以使用:
@foreach($items as $item)
@if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
@else
<h5>{{$item->program_name}}</h5>
@endif
@endforeach