laravel blade foreach continue and break 跳过或跳出循环

laravel blade foreach continue and break 跳过或跳出循环

laravel blade foreach continue and break 跳过或跳出循环

例子:

如果用户id是1就跳过循环,这里我们forelse当没有数据的时候默认输出一些提示信息:
@forelse($data as $item)
    @if($item->id == 1)
        <?php continue;?>
    @endif
    <p>{{$item->name}}</p>
@empty
    <div>还没有用户请添加</div>
@endforelse

第二种方法是自定义一个blade模板的定义:在AppServiceProvider类的boot方法里面添加如下代码:

public function boot()
{
        Blade::directive('continue', function() {
            return "<?php continue; ?>";
        });

        Blade::directive('break', function() { return "<?php break; ?>"; });
}

在blade模板中使用@continue 和 @break即可,当然你可以定义自己喜欢的任何封装

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据