有時候我們的 component 可能會希望能插入比較自由的內容,這時就可以使用 laravel 提供的 slot 來讓我們可以自由地插入內容。

我先建立一個新的 component Card:

php artisan make:component Card

 

Card.php 的部分還是保留一些比較制式放入內容的部分

public $title;
public function __construct($title)
{
  $this->title = $title;
}

 

在 card.blade.php 的部分就使用 $slot 來指定要自由放置內容的地方:

<div class="card">
    <h2 class="h3 p-2">{{ $title }}</h2>
    {{ $slot }}
</div>

 

這樣我們在使用 component 的時候,就可以在標籤內自由的放想放的內容了:

<x-card title="標題">
  hello component
</x-card>

 

有時候我們想要在 component 內插入的區塊可能不只一個,這時我們就可以替 component 命名,以便插入數個區塊的內容:

<div class="card">
    <h2 class="h3 p-2">{{ $title }}</h2>
    {{ $slot }}
    <footer>
        {{$footer}}
    </footer>
</div>

 

像上面我就多設置了一個 $footer 的區塊,那如果要插入內容的話,只要在 x-slot 的地方指定相同的 name 即可:

<x-card title="標題">
  <x-slot name="footer">this is footer</x-slot>
  hello component
</x-card>

這樣在 x-slot 就會插入的 footer 內,而沒有用 x-slot 的標籤標示的部分,則會插入到沒有名字的 slot 內,所以以這個範例來說 this is footer 是會在 hello component 下面的。