php 如何在laravel刀片视图中打破foreach循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45189524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:05:24  来源:igfitidea点击:

How to break a foreach loop in laravel blade view?

phplaravelforeachblade

提问by Sagar Gautam

I have a loop like this:

我有一个这样的循环:

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

I want to break the loop after data display if condition is satisfied.

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

How it can be achieved in laravel blade view ?

如何在 Laravel 刀片视图中实现它?

回答by Alexey Mezenin

From the Blade docs:

来自Blade 文档

When using loops you may also end the loop or skip the current iteration:

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

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

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

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

回答by Bilal Ahmed

you can break like this

你可以这样休息

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

        @endif
    @endforeach

回答by Hiren Gohel

Basic usage

基本用法

By default, blade doesn't have @breakand @continuewhich are useful to have. So that's included.

默认情况下,blade 没有@break@continue哪些是有用的。所以这包括在内。

Furthermore, the $loopvariable is introduced inside loops, (almost) exactly like Twig.

此外,该$loop变量是在循环内部引入的,(几乎)与 Twig 完全一样。

Basic Example

基本示例

@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