如何仅显示 Laravel Blade 模板中集合中第一项的内容

How to display something only for the first item from the collection in Laravel Blade template

我在 Blade 模板中有一个 @foreach 循环,需要对集合中的第一项应用特殊格式。如何添加条件以检查这是否是第一项?

@foreach($items as $item)
    <h4>{{ $item->program_name }}</h4>
@endforeach`

只取键值

@foreach($items as $index => $item)
    @if($index == 0)
        ...
    @endif
    <h4>{{ $item->program_name }}</h4>
@endforeach

苏豪区,

最快的方法是将当前元素与数组中的第一个元素进行比较:

@foreach($items as $item)
    @if ($item == reset($items )) First Item: @endif
    <h4>{{ $item->program_name }}</h4>
@endforeach

否则,如果它不是关联数组,您可以按照上面的答案检查索引值 - 但如果数组是关联数组,那将不起作用。

Laravel 5.3foreach 循环中提供了一个 $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-loop-variable

Liam Wiltshire 的回答的主要问题是性能,因为:

  1. reset($items) 在每个循环中一次又一次地倒回 $items 集合的指针。 . 总是有相同的结果。

  2. $itemreset($item)的结果都是对象,所以$item == reset($items) 需要对其属性进行全面比较...需要更多处理器时间。

一个更有效和优雅的方法 -正如 Shannon 所建议的那样s- 是使用 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 对 [= 周围的双引号进行编码32=]特殊 字符串.

此致。

要获取 Laravel 中集合的第一个元素,您可以使用:

@foreach($items as $item)
    @if($item == $items->first()) {{-- first item --}}
        <h4>{{$item->program_name}}</h4>
    @else
        <h5>{{$item->program_name}}</h5>
    @endif
@endforeach            

如果您只需要第一个元素,您可以在 @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

Laravel 7.* 提供了一个 first() 辅助函数。

{{ $items->first()->program_name }}

*请注意,我不确定这是何时引入的。因此,它可能不适用于早期版本。

只是在documentation here中简单提及。

从 Laravel 7.25 开始,Blade 现在包含一个新的 @once 组件,因此您可以这样做:

@foreach($items as $item)
    @once
    <h4>{{ $item->program_name }}</h4>  // Displayed only once
    @endonce
    // ... rest of looped output
@endforeach

你可以通过这种方式完成。

collect($users )->first();