Laravel Blade 中的动态行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30142864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic number of rows in Laravel Blade
提问by ka ern
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?
我怎么做?
回答by Adnan
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. Example:
在视图中使用原始 PHP 并不是最好的解决方案。例子:
<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>
回答by smozgur
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>
回答by Unni K S
回答by Kenneth mwangi
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>
`
`
回答by Hussaini Mamman
Starting from Laravel 5.3, this has been become a lot easier. Just use the $loop object from within a given loop. You can access $loop->index or $loop->iteration. Check this answer: https://laracasts.com/discuss/channels/laravel/count-in-a-blade-foreach-loop-is-there-a-better-way/replies/305861
从 Laravel 5.3 开始,这变得容易多了。只需在给定循环中使用 $loop 对象。您可以访问 $loop->index 或 $loop->iteration。检查这个答案:https: //laracasts.com/discuss/channels/laravel/count-in-a-blade-foreach-loop-is-there-a-better-way/replies/305861
回答by Sanchit
Just take a variable before foreach()
like $i=1
. And increment $i
just before foreach()
ends. Thus you can echo $i
in the desired <td></td>
只需在foreach()
like之前取一个变量$i=1
。并$i
在foreach()
结束前增加。因此,您可以echo $i
在所需的<td></td>
回答by mspreitz
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>