我在Blade模板中有一个@foreach循环,需要对集合中的第一项应用特殊格式。如何添加条件语句来检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
我在Blade模板中有一个@foreach循环,需要对集合中的第一项应用特殊格式。如何添加条件语句来检查这是否是第一项?
@foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
@endforeach`
@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
$items
不是一个数组,这仍将失败 :)。 - Gumma Mocciaro@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 }}
*请注意,我不确定这是何时引入的。因此,在早期版本中可能无法使用。
该功能仅在文档中简要提到。
@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($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