如何在laravel blade view中打破foreach循环?

jfewjypa  于 2023-05-19  发布在  其他
关注(0)|答案(6)|浏览(291)

我有一个这样的循环:

@foreach($data as $d)
    @if(condition==true)
        {{$d}}
        // Here I want to break the loop in above condition true.
    @endif
@endforeach

如果条件满足,我想在数据显示后中断循环。
如何在laravel中实现blade视图?

cotxawn7

cotxawn71#

从Blade文档:
使用循环时,您也可以结束循环或跳过当前迭代:

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

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

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

xqnpmsa82#

你可以像这样折断

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

qjp7pelc3#

基本用法
默认情况下,刀片式服务器没有@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
ruarlubt

ruarlubt4#

官方文档说:* 使用循环时,也可以使用**@continue@break**指令结束循环或跳过当前迭代:*

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

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

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

@endforeach

emeijp43

emeijp435#

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

lx0bsm1f6#

这个方法对我很有效

@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

相关问题