简体   繁体   English

调用集合时如何在laravel刀片html属性中添加索引

[英]how to add index in laravel blade html attribute while calling collection

I am calling categories collection from controller and displaying in the blade in foreach loops我正在从控制器调用类别集合并在 foreach 循环中的刀片中显示

@foreach ($categories as $category)
    @foreach ($category->subcategories as $subcategory)
         <a class="a.toggle-vis" data-column="1">{{ $subcategory->name }}</a>
    @endforeach
@endforeach

I need to add index numbers generated in the loop from 1 in data-column value我需要从数据列值中的 1 添加在循环中生成的索引号

data-column="1"
data-column="2"
data-column="3"

so on....in等等......在

For doing this you need to make a variable for counting after that you should pass that variable to view like below.为此,您需要创建一个用于计数的变量,然后您应该将该变量传递给如下所示的视图。

I am inside a method我在一个方法里面

public function getSingle($slug){
        $category= Post::where('slug','=',$slug)->first();
        if ($post != null) {
            $counter = 0;
            return view('blog.single')->withCategories($category)->withCounter($counter);

        } else {
            return view('error.error404');
    }

 }

After that you should access that Counter variable in view like below之后,您应该在视图中访问该Counter变量,如下所示

    @foreach ($categories as $category)
      @foreach ($category->subcategories as $subcategory)
         <a class="a.toggle-vis" data-column="{{$counter++}}">{{ $subcategory->name }}</a>
      @endforeach
   @endforeach

The classic for will do经典之作

@foreach ($categories as $category)
    @for ($i = 0; $i < count($category->subcategories); $i++)
       <a class="a.toggle-vis" data-column="{{$i}}">{{ $category->subcategories[$i]->name }}</a>
    @endfor
@endforeach

For a shorter one, I think, we can do something like this.对于较短的,我认为,我们可以做这样的事情。 A little bit dirty in view but in the small snippet, it should be okay.看起来有点脏,但在小片段中,应该没问题。

{{ !($index = 1) }}
@foreach ($categories as $category)
    @foreach ($category->subcategories as $subcategory)
         <a class="a.toggle-vis" data-column="{{ $index++ }}">{{ $subcategory->name }}</a>
    @endforeach
@endforeach

Use this simple solution (Laravel method):使用这个简单的解决方案(Laravel 方法):

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

It will automatically increment, in every loop iteration.它会在每次循环迭代中自动递增。
Check docs:检查文档:
The Loop Variable循环变量

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

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