laravel 视图流程控制,if switch for loop

it2025-04-14  11

流程控制

除了模板继承和数据显示之外,Blade 还为常用的 PHP 流程控制提供了便利操作,例如条件语句和循环,这些快捷操作提供了一个干净、简单的方式来处理 PHP 的流程控制,同时保持和 PHP 相应语句的相似性。

If 语句

可以使用 @if , @elseif , @else 和 @endif 来构造 if 语句,这些指令的功能和 PHP 相同:

@if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif

为方便起见,Blade 还提供了 @unless 指令,表示除非:

@unless (Auth::check()) You are not signed in. @endunless

此外,Blade 还提供了 @isset 和 @empty 指令,分别对应 PHP 的 isset 和 empty 方法:

@isset($records) // $records is defined and is not null... @endisset @empty($records) // $records is "empty"... @endempty

认证指令

@auth 和 @guest 指令可用于快速判断当前用户是否登录:

@auth // 用户已登录... @endauth @guest // 用户未登录... @endguest

如果需要的话,你也可以在使用 @auth 和 @guest 的时候指定认证 guard:

@auth('admin') // The user is authenticated... @endauth @guest('admin') // The user is not authenticated... @endguest

Section 指令

你可以使用 @hasSection 指令判断某个 section 中是否有内容:

@hasSection('navigation') <div class="pull-right"> @yield('navigation') </div> <div class="clearfix"></div> @endif

Switch 语句

switch 语句可以通过 @switch,@case,@break,@default 和 @enswitch 指令构建:

@switch($i) @case(1) First case... @break @case(2) Second case... @break @default Default case... @endswitch

循环

除了条件语句,Blade 还提供了简单的指令用于处理 PHP 的循环结构,同样,这些指令的功能和 PHP 对应功能完全一样:

@for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor @foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach @forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse @while (true) <p>I'm looping forever.</p> @endwhile

注:在循环的时候可以使用 $loop 变量获取循环信息,例如是否是循环的第一个或最后一个迭代。

使用循环的时候还可以结束循环或跳出当前迭代:

@foreach ($users as $user) @if ($user->type == 1) @continue @endif <li>{{ $user->name }}</li> @if ($user->number == 5) @break @endif @endforeach

还可以使用指令声明来引入条件:

@foreach ($users as $user) @continue($user->type == 1) <li>{{ $user->name }}</li> @break($user->number == 5) @endforeach

$loop变量

在循环的时候,可以在循环体中使用 $loop 变量,该变量提供了一些有用的信息,比如当前循环索引,以及当前循环是不是第一个或最后一个迭代:

@foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is user {{ $user->id }}</p> @endforeach

如果你身处嵌套循环,可以通过 $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

$loop 变量还提供了其他一些有用的属性:

属性描述$loop->index当前循环迭代索引 (从0开始)$loop->iteration当前循环迭代 (从1开始)$loop->remaining当前循环剩余的迭代$loop->count迭代数组元素的总数量$loop->first是否是当前循环的第一个迭代$loop->last是否是当前循环的最后一个迭代$loop->depth当前循环的嵌套层级$loop->parent嵌套循环中的父级循环变量

转载于:https://www.cnblogs.com/vania/p/9552576.html

最新回复(0)