30

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

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

9 回答 9

96

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

文档:https ://laravel.com/docs/5.3/blade#the-loop-variable

于 2016-10-16T00:50:48.417 回答
12

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.

于 2015-11-25T16:52:54.613 回答
8

Just take the key value

@foreach($items as $index => $item)
    @if($index == 0)
        ...
    @endif
    <h4>{{ $item->program_name }}</h4>
@endforeach
于 2015-11-25T16:52:38.787 回答
5

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

@foreach($items as $item)
    @once
    <h4>{{ $item->program_name }}</h4>  // Displayed only once
    @endonce
    // ... rest of looped output
@endforeach
于 2021-01-28T16:17:44.820 回答
5

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

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

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

此处的文档中仅简要提及了它。

于 2020-07-23T10:05:57.777 回答
3

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

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

  2. $itemreset($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 编码。

问候。

于 2018-01-29T11:55:44.850 回答
1

如果您只需要可以@break@foreachor中使用的第一个元素,请@if参见示例:

@foreach($media as $m)
    @if ($m->title == $loc->title) :
        <img class="card-img-top img-fluid" src="images/{{ $m->img }}">
          
        @break
    @endif
@endforeach
于 2020-07-18T06:55:22.267 回答
0

你可以这样做。

collect($users )->first();
于 2022-01-11T12:53:34.067 回答
-3

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

@foreach($items as $item)
    @if($item == $items->first()) {{-- first item --}}
        <h4>{{$item->program_name}}</h4>
    @else
        <h5>{{$item->program_name}}</h5>
    @endif
@endforeach            
于 2018-03-12T17:58:28.057 回答