2016年10月30日 星期日

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 " {$empty} = true; foreach{$expression}: {$empty} = false; ?>";
}

from : https://laravel-china.org/topics/2342

沒有留言:

wibiya widget