Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

InfoRR's avatar
Level 13

Create a component with a dynamic number of slots

I am trying to create a "bootstrap tabs" component. I was thinking of passing the number and names of the tab links as an array (easy).

Now the problem is that I need the tab content to be a loop over that same array to create a dynamic named slots. This is not working and always returning the slot name rather than the slot content.

<nav>
  <div class="nav nav-tabs" role="tablist">
    @foreach ($tabs as $tab)
        <a class="nav-link" id="nav-{{$tab}}-tab" data-bs-toggle="tab" data-bs-target="#nav-{{$tab}}" type="button" role="tab" aria-controls="{{$tab}}" aria-selected="false">{{$tab}}</a>
    @endforeach
  </div>
</nav>
<div class="tab-content"  id="{{$id}}">
    @foreach ($slots as $slot)
        <div class="tab-pane fade" id="nav-{{$tab}}" role="tabpanel" aria-labelledby="nav-{{$tab}}-tab">
            {{ $slot }}
        </div>
    @endforeach
</div>

and to use it this way:

<x-tabs id="test-tabs" :tabs="$tabs" :slots="$slots">
    <x-slot name="maincontent">
        // some content
    </x-slot>
    <x-slot name="tab_gallery">
        // different content
     </x-slot>
</x-tabs>
0 likes
3 replies
samehdev's avatar

try this: @foreach ($tabs as $key => $tab)

                 <a class="nav-link" id="nav-{{$key}}-tab" data-bs-toggle="tab" data-bs-target="#nav-{{$key}}" type="button" role="tab" aria-controls="{{$key}}" aria-selected="false">{{$tab}}</a>
      @endforeach
   </div>
  </nav>
     <div class="tab-content"  id="{{$id}}">
       @foreach ($slots as $key => $slot)
             <div class="tab-pane fade" id="nav-{{$tabs[$key]}}" role="tabpanel" aria-labelledby="nav-{{$tabs[$key]}}-tab">
              {{ $slot }}
            </div>
        @endforeach
      </div>
2 likes
InfoRR's avatar
Level 13

Thank you. I liked the idea of associative array (tab_name=>slot). I applied it but that didn't fix the problem. My problem was that in the slot it prints the slot name rather than the slot content.

I found out that I should add double $ before the slot name like this:

@foreach ($slots as $key => $slot)
    <div class="tab-pane fade" id="nav-{{$tabs[$key]}}" role="tabpanel" aria-labelledby="nav-{{$tabs[$key]}}-tab">
        {{ $$slot }}
    </div>
@endforeach 

Thank you for your answers and the hints!

1 like

Please or to participate in this conversation.