Laravel Tips 之 forelse(顺便测试一下社区新版发帖功能)
本文最早发表于本人博客 Laravel Tips 之 forelse
我们在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 "<?php {$empty} = true; foreach{$expression}: {$empty} = false; ?>";
}
新版发帖功能用起来如何 :smile:
@Aufree 还是那么的顺畅和舒服 :+1:
多亏你这个帖子,发现代码高亮有点问题,解决了 :smile: :beers:
@Summer good job