[英]Laravel Blade Template - How to use incremental variable in foreach loop
我需要知道是否有一个laravel刀片方式来执行以下操作而不使用PHP标记。
<?php $i = 1; ?>
@foreach($rows as $row)
//do something
<?php $i++; ?>
@endforeach
正如您所看到的,代码看起来很难看标签,浪费时间来编写额外的标签。
使用索引
@foreach($rows as $index=>$row)
{{$index}}
@endforeach
如果你想定义一些变量然后使用@php($counter=0)
@php($counter=0)
@foreach($rows as $index=>$row)
$counter=$counter+2;
{{$counter}}
@endforeach
如果你使用laravel> 5.4,那么你可以使用$ 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
同样,您可以不再需要重新发明轮子。
@foreach($rows as $row)
//do something
{{ $loop->index }}
@endforeac
希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.