and*_*79h 1 php templates loops laravel 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
Run Code Online (Sandbox Code Playgroud)
现在,这<?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
Run Code Online (Sandbox Code Playgroud)
在某些情况下,将PHP代码嵌入到视图中非常有用.您可以使用Blade
@php指令在模板中执行普通PHP块
https://laravel.com/docs/5.5/blade#php