我在 Blade 模板中有一个 @foreach 循环,需要对集合中的第一项应用特殊格式。如何添加条件来检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
我在 Blade 模板中有一个 @foreach 循环,需要对集合中的第一项应用特殊格式。如何添加条件来检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
Laravel 5.3在循环中提供了一个$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
SoHo,
The quickest way is to compare the current element with the first element in the array:
@foreach($items as $item)
@if ($item == reset($items )) First Item: @endif
<h4>{{ $item->program_name }}</h4>
@endforeach
Or otherwise, if it's not an associative array, you could check the index value as per the answer above - but that wouldn't work if the array is associative.
Just take the key value
@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
注意使用{!!
and!!}
标记而不是符号来避免特殊字符串{{
}}
周围双引号的 html 编码。
问候。
如果您只需要可以@break
在@foreach
or中使用的第一个元素,请@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();
要在 Laravel 中获取集合的第一个元素,可以使用:
@foreach($items as $item)
@if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
@else
<h5>{{$item->program_name}}</h5>
@endif
@endforeach