Laravel 的 Blade 中的循环变量

Loop variables in Laravel's Blade

我在 Laravel 的 Blade 模板中做了很多循环,有时,我必须记住一些条件,比如 $found 或 $needToSave,诸如此类。

这是一个小例子:

<?php $found = false; ?>
@foreach ($users as $user)
    @foreach ($user->posts as $post)

        @if ($post->something == "value")
            <?php $found = true; ?>
        @endif

        @if ($loop->parent->last)
            @if ($found)
                I really found something! Do something special!
            @endif
        @endif

    @endforeach
@endforeach

现在,<?php $found = false|true ?> 部分有更好的方法吗? 对我来说,这似乎是不干净的,我正在寻找一个更干净的解决方案,它与模板引擎一起发挥作用。我知道 @php 但这对我来说似乎很难看。有什么可以在引擎中分配本地变量吗?

干杯

如果以后不需要该变量,可以将代码重构为:

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->last && $post->something === 'value')
            I really found something! Do something special!
        @endif
    @endforeach
@endforeach

以后要用的话可以用@php and @endphp

In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template

https://laravel.com/docs/5.5/blade#php