如何在Laravel Blade视图中终止foreach循环?

63
我有一个像这样的循环:
@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        // Here I want to break the loop in above condition true.
    @endif
@endforeach

如果条件满足,我想在数据显示后中断循环。

如何在Laravel Blade视图中实现?


8
在使用@endif之前,请使用@break - Hiren Gohel
6个回答

133

来自Blade文档:

使用循环时,您还可以结束循环或跳过当前迭代:

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

@break 在循环中的使用方式与 break 的其他用法类似吗? - Sagar Gautam

6

你可以像这样打破

@foreach($data as $d)
    @if($d === "something")
        {{$d}}
        @if(condition)
            @break
        @endif
    @endif
@endforeach

5

基本用法

默认情况下,Blade 没有 @break@continue 这两个非常有用的语句。因此这里已经包含了它们。

此外,在循环中引入了 $loop 变量,与 Twig 几乎完全相同。

基本示例

@foreach($stuff as $key => $val)
     $loop->index;       // int, zero based
     $loop->index1;      // int, starts at 1
     $loop->revindex;    // int
     $loop->revindex1;   // int
     $loop->first;       // bool
     $loop->last;        // bool
     $loop->even;        // bool
     $loop->odd;         // bool
     $loop->length;      // int

    @foreach($other as $name => $age)
        $loop->parent->odd;
        @foreach($friends as $foo => $bar)
            $loop->parent->index;
            $loop->parent->parentLoop->index;
        @endforeach
    @endforeach 

    @break

    @continue

@endforeach

这就是我一直在寻找的 $loop->last; - Yasser CHENIK
@YasserCHENIK 很高兴能帮助你 :) - Hiren Gohel

1

官方文档表示:使用循环时,您还可以使用 @continue@break 指令来结束循环或跳过当前迭代:

@foreach ($users as $user)
@if ($user->type == 1)
    @continue
@endif

<li>{{ $user->name }}</li>

@if ($user->number == 5)
    @break
@endif

@endforeach


1

这个方法对我有效

@foreach(config('app.languages') as $lang)
    @continue(app()->getLocale() === $lang['code'])
    <div class="col">
       <a href="#" class="btn w-100">
          {!! $lang['img'] !!}&nbsp;&nbsp;{{ $lang['name'] }}
       </a>
    </div>
@endforeach

0
@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        @break // Put this here
    @endif
@endforeach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接