Laravel 控制结构

示例

Blade为常见的PHP控制结构提供了方便的语法。

每个控制结构@[structure]均以开头和结尾@[endstructure]。注意,在标记中,我们只是键入普通的HTML,并使用Blade语法包括变量。

有条件的

'如果'陈述

@if ($i > 10)
    <p>{{ $i }} is large.</p>
@elseif ($i == 10)
    <p>{{ $i }} is ten.</p>
@else
    <p>{{ $i }} is small.</p>
@endif

除非声明

(“如果不是”的简短语法。)

@unless ($user->hasName())
    <p>A user has no name.</p>
@endunless

循环

“当”循环

@while (true)
    <p>I'm looping forever.</p>
@endwhile

“ Foreach”循环

@foreach ($users as $id => $name)
    <p>User {{ $name }} has ID {{ $id }}.</p>
@endforeach

“ Forelse”循环

(与'foreach'循环相同,但添加了一个特殊@empty指令,该指令在迭代的数组表达式为空时执行,以显示默认内容。)

@forelse($posts as $post)
    <p>{{ $post }} is the post content.</p>
@empty
    <p>There are no posts.</p>
@endforelse


在循环内,$loop将提供一个特殊变量,其中包含有关循环状态的信息:

属性描述
$loop->index当前循环迭代的索引(从0开始)。
$loop->iteration当前循环迭代(从1开始)。
$loop->remaining其余的循环迭代。
$loop->count数组中要迭代的项目总数。
$loop->first这是否是循环的第一次迭代。
$loop->last这是否是循环中的最后一次迭代。
$loop->depth当前循环的嵌套级别。
$loop->parent在嵌套循环中,父级的循环变量。

例:

@foreach ($users as $user)
  @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            This is first iteration of the parent loop.
        @endif
    @endforeach
@endforeach


从Laravel 5.2.22开始,我们还可以使用指令@continue和@break

属性描述
@continue停止当前迭代并开始下一个迭代。
@break停止当前循环。

范例:

@foreach ($users as $user)
    @continue ($user->id == 2)
        <p>{{ $user->id }} {{ $user->name }}</p>
    @break ($user->id == 4)
@endforeach

然后(假设5个以上的用户按ID排序并且没有ID缺失),页面将呈现

1 Dave
3 John
4 William