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

时间:2018-06-28 05:51:19

标签: laravel loops variables laravel-blade

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

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

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

3 个答案:

答案 0 :(得分:5)

使用索引

public void captureMapScreen() {
    SnapshotReadyCallback callback = new SnapshotReadyCallback() {

        @Override
        public void onSnapshotReady(Bitmap snapshot) {
            try {
                mView.setDrawingCacheEnabled(true);
                Bitmap backBitmap = mView.getDrawingCache();
                Bitmap bmOverlay = Bitmap.createBitmap(
                        backBitmap.getWidth(), backBitmap.getHeight(),
                        backBitmap.getConfig());
                Canvas canvas = new Canvas(bmOverlay);
                canvas.drawBitmap(backBitmap, 0, 0, null);
                canvas.drawBitmap(snapshot, new Matrix(), null);
                FileOutputStream out = new FileOutputStream(
                        Environment.getExternalStorageDirectory()
                                + "/MapScreenShot"
                                + System.currentTimeMillis() + ".png");

                bmOverlay.compress(Bitmap.CompressFormat.PNG, 90, out);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    mMap.snapshot(callback);

}

如果要定义一些变量,请使用@foreach($rows as $index=>$row) {{$index}} @endforeach

@php($counter=0)

答案 1 :(得分:1)

如果您使用的是laravel> 5.4,则可以使用$loop variable来获取索引。

@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

希望这会有所帮助

答案 2 :(得分:0)

尝试$ loop->迭代

 @foreach($rows as $row)
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ $row->item1}}</td>
                <td>{{ $row->item2}}</td>
            </tr>
 @endforeach

结果将是这样

---------------------------------
Si#     |    item 1    |  item2 |
---------------------------------
1       |    AAA       |  111   |
2       |    BBB       |  222   |
---------------------------------