Laravel 4其他声明

时间:2013-07-31 14:51:43

标签: laravel laravel-4

我遇到了问题。 Blade未在@else语句中执行代码。这是我的代码(也就是表格):

        @extends('base')
@section('title', 'Who is online?')
@endsection
@section('main')

<div class="doc-content-box">
  <table class="table table-striped table-condensed">
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th>Level</th>
        <th>Vocation</th>
        <th>Date registered</th>
        <th>Role</th>
        </tr>
  </thead>
<tbody>

    @if(!empty($results))
        <?php $count = 0;?>
        @foreach($results as $result) 
      <?php $count++;?>
      <tr>

        <td>{{ $count }}. </td>

        <td>{{ $result->name }}</td>

        <td>{{ $result->level }}</td>

        <td><?php if($result->vocation == 1){ 
echo "Sorcerer"; 
}else if($result->vocation == 2){
echo 'Druid';
}else if($result->vocation == 3){
echo 'Paladin';
}else if($result->vocation == 4){
echo 'Knight';
}else if($result->vocation == 5){
echo 'Master Sorcerer';
}else if($result->vocation == 6){
echo 'Elder Druid';
}else if($result->vocation == 7){
echo 'Royal Paladin';
}else{
echo 'Elite Knight';
}?></td>

        <td>{{ $result->created_at }}</td>

        <td><?php if($result->group_id == 1){ 
echo "Player"; 
}else if($result->group_id == 2){
echo 'Gamemaster';
}else if($result->group_id == 3){
echo 'God';
}?></td>

      </tr>
      @endforeach 
@else

<td>{{ "There are no users online." }}</td>

@endif
</tbody>

  </table>
</div>
</div>

@endsection

它不会执行没有在线玩家。我也尝试在<tr></tr>之间添加它,同时查看了Blade template not executing @else clause,尝试了类似:<td>'There are no players online.'</td>,但它仍然没有出现。

另外,我能用三元运算符切换所有那些php if语句吗?如果是这样,我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

原因是因为您的if语句位于foreach语句中,因此永远不会执行。如果您将foreach移到if块内,它应该可以正常工作。

---更多

我实际上只是做了你正在做的事情并发现了问题。您在empty()上调用$results这是一个对象,而不是一个数组,它是一个Collection对象。正确的方法是使用count()方法。所以像这样:

@if($results->count() > 0)
    @foreach($results as $result)
        ...
    @endforeach
@else
    <p>Nothing found!</p>
@endif

答案 1 :(得分:2)

这是在laravel中的刀片模板中编写三元运算符的方法之一。

{{{$collectionObject->filed_name ==1 ? 'Yes' : 'No' }}}