[英]Dynamic number of rows in Laravel Blade
I want a dynamic number of rows in a table like this.我想要像这样的表中的动态行数。
number name
1 Devy
This my Blade template.这是我的 Blade 模板。
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $value)
<tr>
<td></td>
<td>{{$value->name}}</td>
</tr>
@endforeach
</tbody>
How do I do that?我怎么做?
Try $loop->iteration
variable.试试
$loop->iteration
变量。
` `
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $value)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$value}}</td>
</tr>
@endforeach
</tbody>
` `
This is correct:这是对的:
@foreach ($collection as $index => $element)
{{$index}} - {{$element['name']}}
@endforeach
And you must use index+1 because index starts from 0.并且您必须使用 index+1,因为 index 从 0 开始。
Using raw PHP in view is not the best solution.在视图中使用原始 PHP 并不是最好的解决方案。 Example:
例子:
<tbody>
<?php $i=1; @foreach ($aaa as $value)?>
<tr>
<td><?php echo $i;?></td>
<td><?php {{$value->name}};?></td>
</tr>
<?php $i++;?>
<?php @endforeach ?>
in your case:在你的情况下:
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $index => $value)
<tr>
<td>{{$index}}</td> // index +1 to begin from 1
<td>{{$value}}</td>
</tr>
@endforeach
</tbody>
Use a counter and increment its value in loop:使用计数器并在循环中递增其值:
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
<?php $i = 0 ?>
@foreach ($aaa as $value)
<?php $i++ ?>
<tr>
<td>{{ $i}}</td>
<td>{{$value->name}}</td>
</tr>
@endforeach
</tbody>
Use $loop variable使用 $loop 变量
refer this link Loop Variable请参阅此链接循环变量
Starting from Laravel 5.3, this has been become a lot easier.从 Laravel 5.3 开始,这变得容易多了。 Just use the $loop object from within a given loop.
只需在给定循环中使用 $loop 对象。 You can access $loop->index or $loop->iteration.
您可以访问 $loop->index 或 $loop->iteration。 Check this answer: https://laracasts.com/discuss/channels/laravel/count-in-a-blade-foreach-loop-is-there-a-better-way/replies/305861
检查这个答案: https : //laracasts.com/discuss/channels/laravel/count-in-a-blade-foreach-loop-is-there-a-better-way/replies/305861
Just take a variable before foreach()
like $i=1
.只需在
foreach()
之前取一个变量,例如$i=1
。 And increment $i
just before foreach()
ends.并在
foreach()
结束之前增加$i
。 Thus you can echo $i
in the desired <td></td>
因此,您可以在所需的
<td></td>
echo $i
try the following:尝试以下操作:
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $index => $value)
<tr>
<td>{{$index}}</td>
<td>{{$value}}</td>
</tr>
@endforeach
</tbody>
You can Use it like this in Blade.你可以在 Blade 中像这样使用它。 I hope this will help.
我希望这将有所帮助。
<thead>
<th>number</th>
<th>name</th>
</thead>
<tbody>
@foreach ($aaa as $index => $value)
<tr>
<td>{{$index +1}}</td>
<td>{{$value}}</td>
</tr>
@endforeach
</tbody>
Note: {{$index +1}}
since $index
starts from 0注意:
{{$index +1}}
因为$index
从 0 开始
Laravel 8 - Laravel 8 -
<?php $serial = "1"; ?> - Before @foreach loop
<td>{{ $serial++ }}</td> - Inside @foreach loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.