我在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代码嵌入视图中很有用。您可以使用Blade
@php
指令在模板中执行一个纯PHP块
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句