【问题标题】:Laravel access nested component / $slot IndexLaravel 访问嵌套组件 / $slot 索引
【发布时间】:2021-07-13 15:46:55
【问题描述】:

在 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 组件。

谢谢。

【问题讨论】:

    标签: php laravel laravel-blade


    【解决方案1】:

    $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

    【讨论】:

    • 嘿,是的,但我的问题是我无法在 $slots 上循环,$slots 不作为变量存在,只有 $slot 存在。
    • 插槽从何而来?你检查控制器了吗?
    • slots 来自背包 cms,就像我在问题中显示的示例一样。如果我在 step 刀片内打印 slot 没关系,但在渲染它之前我想将 prop step 与 index 相关联
    • 所以如果我理解正确$slot 变量包含您在index.blade.php 中提供的内容?
    • x-step-card 是你自己制作的还是背包提供的?如果提供了组件文档的链接,您能否提供一个链接?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2018-02-10
    • 2023-04-07
    • 2020-04-25
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多