Laravel Blade模板-如何在foreach循环中使用增量变量

塔希尔·阿弗里迪(Tahir Afridi)

我需要知道是否有laravel刀片方式可以在不使用PHP标记的情况下执行以下操作。

<?php $i = 1; ?>
@foreach($rows as $row)
   //do something
   <?php $i++; ?>
@endforeach

如您所见,代码中的标签看起来很丑陋,并且浪费时间编写额外的标签。

阿德南·穆姆塔兹(Adnan Mumtaz)

如果您使用的是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

希望这可以帮助

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章