在Laravel-foreach循环中设置变量



我刚刚开始使用这个框架。在普通PHP中,在打开foreach之后,我会设置变量,然后关闭PHP标记,但根据我的计算结果,你必须执行Laravel@foreach标记,然后打开和关闭@php。有没有办法解决这个问题,因为它似乎需要大量额外的工作和代码?

@foreach($steps as $row)
@php
$title = $row->title;
$text = $row->text;
$i = 1;
@endphp
<div class="steps-item grid-wrap">
<div class="number"
@if($text || $title)
<div class="text-wrap">
@if($title)
<h2>{{$title}}</h2>
@endif
{!! $text !!}
</div>
@php
$i++;
@endphp
@endif
</div>{{--END steps-item--}}
@endforeach

由于blade不是PHP,您必须返回到带有该指令的PHP。但在您的情况下,您可以设置/使用变量,而无需这样做:

@foreach($steps as $i => $row)
<div class="steps-item grid-wrap">
<div class="number"
@if($text || $title)
<div class="text-wrap">
@if($title)
<h2>{{ $row->title }}</h2>
@endif
{!! $row->text !!}
</div>
@php
$i++;
@endphp
@endif
</div>{{--END steps-item--}}
@endforeach

如果您仍然想设置变量,有一个名为alexdover/blade-set的Laravel包。但正如@brombier所指出的,在大多数情况下,强烈建议在将所有必要的变量传递给视图之前,在控制器中设置这些变量。

使用laravel提供的循环变量:

$loop->iteration    The current loop iteration (starts at 1).

它将在每次循环迭代中自动递增。

e.g:
First iteration = $loop->iteration => 1 ;
Second iteration = $loop->iteration => 2 ;
so on until loop ends.

检查文档:环路变量

您可以使用sizeof($steps(的@for指令,如下所示:

@for($i=0; $i<= sizeof($steps)-1; $i++)
@endfor

@foreach($steps作为$row(

<div class="steps-item grid-wrap">
<div class="number">
<div class="text-wrap">
@if ($row->title != '')
<h2>{{$row->title}}</h2>
/* if you want to display another title when its blank you can 
use if-else here otherwise not need to use if conditions for 
title and text */
@endif
@if ($row->text != '')
{!! $row->text !!}
@endif
</div>
</div>
</div>

@每个的末端

{{--例如,您有$steps值,如

$steps=阵列([0]->1.[1] ->'标题',[2] ->'文本');

如果你想要这个数组键值对,你必须像这样使用@foreach@foreach($steps as$key=>$value(@每个的末端

只能在@foreach循环中使用键值--}}

最新更新