1. 在模版中我们可以使用@if @else @elseif @endif 来设置条件判断;
return view( 'user ', [
'num ' => 20
]);
{{--单一判断 --}}
@if($num > 10)
num 大于 10
@endif
{{--带 else 判断 --}}
@if($num > 10)
num 大于 10
@else
num 小于 10
@endif
{{--带 elseif 判断 --}}
@if($num > 10)
num 大于 10
@elseif($num > 5)
num 大于 5
@else
num 小于 5
@endif
2. @unless @endunless 相当于@if 取反的操作,可通过编译文件参看;
@unless($num > 10)
num 小于 10
@endunless
3. @isset 判断变量是否存在 @empty 判断变量是否为空;
@isset($name)
变量存在
@endisset
@empty($name)
变量为空
@endempty
4. @switch 实现条件分支判断,包含@case @break @default;
@switch($num)
@case(1)
1
@break
@case(4)
4
@break
@default
不存在
@endswitch
二.循环遍历
1. @for 循环,适合数值的循环;
@for($i =0; $i <= 10; $i++)
{{$i}}
@endfor
2. @foreach 适合对象的变量循环;
@foreach($obj as $user)
{{$user->username}}
@endforeach
3. @continue 可以跳出当且迭代,@break 跳出循环;
@foreach($obj as $user)
@if ($user->username == '樱桃小丸子')
@continue //@break
@endif
{{$user->username}}
@endforeach
PS:变体写法:@continue($user->username == '樱桃小丸子')
4. @white 判断循环; @while($num > 0)
while 循环
{{$num--}}
@endwhile
5. 在循环体内,会有一个@loop 变量,帮助我们处理各种问题;
@foreach($obj as $user)
@if($loop->first)
[起始数据之前]
@endif
@if($loop->last)
[末尾数据之前]
@endif
{{$user->username}} --
@endforeach
属性 | 说明 |
$loop->index | 当前迭代的索引 (从 0 开始) |
$loop->iteration | 当前循环迭代 (从 1 开始) |
$loop->remaining | 循环中剩余迭代的个数 |
$loop->count | 被循环的数组元素个数 |
$loop->first | 是否为循环的第一次迭代 |
$loop->last | 是否为循环的最后一次迭代 |
$loop->even | 是否为循环中的偶数次迭代 |
$loop->odd | 是否为循环中的奇数次迭代 |
$loop->depth | 当前循环的嵌套深度 |
$loop->parent | 嵌套循环中的父循环的循环变量 |
6. PHP 注释和原生的另一种方案@php;
@php
echo 123;
@endphp