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

问题描述 投票:0回答:9

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

@foreach($items as $item)
    <h4>{{ $item->program_name }}</h4>
@endforeach`
php laravel-5.1 laravel-blade
9个回答
120
投票

Laravel 在

$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/10.x/blade#the-loop-variable


12
投票

苏荷区,

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

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

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


8
投票

取键值即可

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

7
投票

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

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

6
投票

Laravel 7.* 提供了

first()
辅助函数。

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

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

这里仅在文档中简要提及


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

请注意使用

{!!

!!}
 标签而不是 
{{
 
}}
 表示法,以避免对 
special 字符串周围的双引号进行 html 编码。

问候。


1
投票
如果您只需要第一个元素,您可以在

@break

@foreach
 中使用 
@if
。参见示例:

@foreach($media as $m) @if ($m->title == $loc->title) : <img class="card-img-top img-fluid" src="images/{{ $m->img }}"> @break @endif @endforeach
    

0
投票
按照这个方法就可以了

collect($users )->first();
    

-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
    
© www.soinside.com 2019 - 2024. All rights reserved.