Laravel 访问嵌套组件/$slot 索引

问题描述

在laravel中,我想访问插槽/插槽的索引... 例如在我的 index.blade.PHP 我有

<x-steps>
    <x-step-card title="step 1" text="Example text for step 1" ></x-step-card>
    <x-step-card title="step 2" text="Example text for step 2" ></x-step-card>
    <x-step-card title="step 3" text="Example text for step 3" ></x-step-card>
</x-steps>

在我的 steps.blade.PHP 中,我有

<div class="container">
  {{$slot}}
</div>

我想将每个插槽项目的索引传递给我的 step-card 组件,尽管 steps.blade.PHP ......这样的东西会很好:

 <div class="container">
      @foreach($slots as $slot)
          <x-step-card step="{{ $loop->index }}" title="{{$slot->title}}" text="{{$slot->text}}"></x-step-card>
      @endforeach
 </div>

问题是$slots 不是变量,我不能循环$slot,因为它返回一个已经呈现的html字符串

PS: foreach 代码是我想做的一个例子,但它不起作用,因为你不能循环 $slot.. 并且 $slots 不存在。

编辑:我正在使用带有 ckeditor 的背包 cms,我想在渲染它之前向我的 x-step-card 组件注入另一个属性

谢谢。

解决方法

可以在 $loop 内部使用 @foreach 变量来访问索引:

<div class="container">
      @foreach($slots as $slot)
          <x-step-card step="{{ $loop->index }}" title="$slot->title" text="$slot->text"></x-step-card>
      @endforeach
 </div>

Laravel foreach docs