我有一个这样的循环:
@foreach($data as $d)
@if(condition==true)
{{$d}}
// Here I want to break the loop in above condition true.
@endif
@endforeach
如果条件满足,我想在数据显示后打破循环。
如何在laravel刀片视图中实现?
答案 0 :(得分:39)
来自Blade docs:
使用循环时,您也可以结束循环或跳过当前循环 迭代:
@foreach ($users as $user)
@if ($user->type == 1)
@continue
@endif
<li>{{ $user->name }}</li>
@if ($user->number == 5)
@break
@endif
@endforeach
答案 1 :(得分:3)
基本用法
默认情况下,刀片没有@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
答案 2 :(得分:2)
你可以像这样打破
@foreach($data as $d)
@if($d=="something")
{{$d}}
@if(codition)
@break
@endif
@endif
@endforeach
答案 3 :(得分:0)
默认情况下,Blade没有@break,但您可以使用这些Laravel Blade扩展来获得您想要的内容:
http://robin.radic.nl/blade-extensions/directives/foreach.html
答案 4 :(得分:0)
@foreach($data as $d)
@if(condition==true)
{{$d}}
@break // Put this here
@endif
@endforeach