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; ?>";
} 
           
         
             
             
             
             
             
             
                     
                     
             
           
           关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: