简体   繁体   English

Laravel Blade:每次将变量增加 1?

[英]Laravel Blade: Increment variable by 1 each time?

Using Laravel blade template, is there a way to include a variable and increase each time in the foreach or what is better approach?使用 Laravel 刀片模板,有没有办法在 foreach 中包含一个变量并每次增加,或者有什么更好的方法?

For example:例如:

@foreach($categories as $category)
  <li><a href="#tab_c1" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach

In the foreach block, the value from #tab_c1 will need to be increase.foreach块中,#tab_c1 中的值需要增加。 eg: #tab_c1, #tab_c2, #tab_c3例如: #tab_c1, #tab_c2, #tab_c3

Add iterator to @foreach :将迭代器添加到@foreach

@foreach($categories as $key => $category)
  <li @if ($key === 0) class="active" @endif>
    <a href="#tab_c{{$key+1}}" role="tab" data-toggle="tab">
      {{$category->name}}
    </a>
  </li>
@endforeach

{{$key+1}} in my example because in PHP iterator starts at 0. {{$key+1}}在我的例子中,因为在 PHP 中迭代器从 0 开始。

In Laravel 5.3 you can use The Loop Variable, $loop->iteration for concrete situation.在 Laravel 5.3 中,您可以使用循环变量,$loop->iteration 用于具体情况。 https://laravel.com/docs/5.3/blade#the-loop-variable https://laravel.com/docs/5.3/blade#the-loop-variable

Exapmle:例子:

@foreach ($questions as $question)
    <tr>
        <th scope="row">{{ $loop->iteration }}</th>
        <td>{{ $question->question }}</td>
        <td>{{ $question->category_id }}</td>
    </tr>
@endforeach

Add a key value in the foreach loop在 foreach 循环中添加键值

@foreach($questions as $key => $question)
<tr>
    <th scope="row">{{ ++$key }}</th>
    <td>{{ $question->question }}</td>
    <td>{{ $question->category_id }}</td>
</tr>
@endforeach

Just use {{ $loop->iteration }} to iterate from 1 to limit只需使用 {{ $loop->iteration }} 从 1 迭代到限制

@foreach($categories as $category)
  <li><a href="#tab_c{{ $loop->iteration }}" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach

Just use the key value.只需使用键值。 For most arrays that will just be 0 up.对于大多数只会为 0 的数组。

@foreach($categories as $i => $category)
  <li{{ $i == 0 ? ' class="active"' : '' }}><a href="#tab_c{{ $i }}" role="tab" data-toggle="tab">{{$category->name}}</a></li>
@endforeach

You can try this:你可以试试这个:

@php($count=0)

@foreach($unit->materials as $m)
    @if($m->type == "videos")
        @php($count++)
    @endif
@endforeach

{{$count}}

This should do the trick @php is same as php open and close tags in laravel这应该可以解决@php与laravel中的php打开和关闭标签相同

<?php $count=0; ?>
 @php($count=0)

<table>
<th>#</th>
<th>Category Name</th>
<tbody>
@php($count=0)
@foreach($categories as $category)
@php($count++)
<tr>
<td>{{$count}}</td>
<td>{{$category->name}}</td>
</tr>
@endforeach
</tbody>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM