我们在Laravel Blade模板中经常在循环输出前先判断一下集合是否有值,然后再
foreach
比如:@if ($posts->count())
@foreach ($posts as $post)
<p>This is post {{ $user->id }}</p>
@endforeach
@else
<p>No posts found.</p>
@endif
其实在Laravel Blade中可以使用
forelse
:@forelse ($posts as $post)
<p>This is post {{ $post->id }}</p>
@empty
<p>No posts found.</p>
@endforelse
它的实现可以在Illuminate/View/Compilers/BladeCompiler.php找到:
/**
* Compile the forelse statements into valid PHP.
*
* @param string $expression
* @return string
*/
protected function compileForelse($expression)
{
$empty = '$__empty_'.++$this->forelseCounter;
return " {$empty} = true; foreach{$expression}: {$empty} = false; ?>";
}
from : https://yuansir-web.com/2016/07/11/laravel-tips-zhi-forelse/
沒有留言:
張貼留言