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 ($users as $id => $name) <p>User {{ $name }} has ID {{ $id }}.</p> @endforeach
(与'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