doumindang2416
2017-07-19 11:43
浏览 153
已采纳

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

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 ?

图片转代码服务由CSDN问答提供 功能建议

我有一个这样的循环:

  @foreach(  $ data as $ d)
 @if(condition == true)
 {{$ d}} 
 //这里我想在上面的条件为true的情况下打破循环。
 @endif 
 @ endforeach 
    
 
 

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

如何在laravel刀片视图中实现?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • doulingzhuang3079 2017-07-19 11:45
    已采纳

    From the Blade docs:

    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
    
    点赞 打赏 评论
  • duan02143 2017-07-19 11:47

    By default Blade does not have @break, but you could use these Laravel Blade extensions to get what you want:

    http://robin.radic.nl/blade-extensions/directives/foreach.html

    点赞 打赏 评论
  • douhunkuang8955 2017-07-19 11:47

    you can break like this

     @foreach($data as $d)
            @if($d=="something")
                {{$d}}
                @if(codition)
                  @break
                @endif
    
            @endif
        @endforeach
    
    点赞 打赏 评论
  • dpojoxa5613 2017-07-19 12:00

    Basic usage

    By default, blade doesn't have @break and @continue which are useful to have. So that's included.

    Furthermore, the $loop variable is introduced inside loops, (almost) exactly like 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
    
    点赞 打赏 评论

相关推荐 更多相似问题