首页 > 解决方案 > 如何在三元运算符中使用@break来打破laravel刀片文件中的foreach循环?

问题描述

我在 Laravel 做项目。我在刀片文件中有 foreach 循环我想在满足条件时打破 foreach 循环,但在这种情况下,我使用了三元运算符,在这个运算符中我想打破我的 foreach 循环。这是我的刀片文件,

@foreach($user->preference_attributes as $attributes)

<tr>
            <th>{{ trans('labels.backend.access.users.tabs.content.overview.location') }}</th>
            <td>{!!($attributes->name == 'location') ? $attributes->pivot->value @break : '' !!}</td>
        </tr>

@endforeach

我已经这样做了,但它不起作用。我不知道如何用三元运算符打破这个。提前致谢。

标签: phplaravel

解决方案


你不能做这个

{!!($attributes->name == 'location') ? $attributes->pivot->value @break : '' !!}

在您的错误情况下,blade被转换为PHP文件,这里有一个非常明显的语法错误,这就是为什么您必须使用PHP语法{{ }}{!! !!}

在此处输入图像描述

这不是真正的原因,我收回这些话,只是因为PHP语法限制不能这样写


转换成 三元运算符的代码是函数的参数时,不可能实现在三元运算符中使用,考虑这个错误示例 你找到问题了吗?<?php echo e($attributes->name == 'location' ? $attributes->pivot->value : ''); ?> e()functionName( 'someStringParameter'; break; )

尝试这个

<tr>
    <th>{{ trans('labels.backend.access.users.tabs.content.overview.location') }}</th>
    <td>
        @if($attributes->name == 'location')
            {!! $attributes->pivot->value !!}
            @break
        @endif
    </td>
</tr>

推荐阅读