Laravel的Blade中的循环变量

andi79h

我在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但这对我来说似乎很丑。是否可以在引擎内分配本地变量?

干杯

阿列克谢·梅曾宁(Alexey Mezenin)

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

@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@endphp

在某些情况下,将PHP代码嵌入视图中很有用。您可以使用Blade@php指令在模板中执行一个纯PHP块

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章