コンポーネントとスロットの使い方を実際にファイルを作成して画面表示を確かめながらまとめています。
ファイルの準備
用意するファイルは2つ。
(1)ビュー
viewsフォルダ直下にcomp-slot.blade.php
を作成。
app > resources > views > comp-slot.blade.php
(2)コンポーネント
componentsフォルダの中にtest.blade.php
を作成。
app > resources > views > components > test.blade.php
ルーティングの設定
app > routes > web.php にルーティングを追記する。
Route::get('test', function () {
return view('comp-slot');
});
パスがtestのURIにアクセスがあったら、ビューファイルcomp-slot.blade.phpを開く。
コンポーネントの使い方
コンポーネントの中身を表示する方法は大きく3つ。
- コンポーネントの中身をそのまま表示。
- 変数slotでデータを渡す。
- 指定したslot名でデータを渡す。
2と3でslotが登場するのがわかりにくい、、それぞれ用途が異なる。
コンポーネントの中身をそのまま表示
コンポーネントをそのまま呼び出して表示する。(データの受け渡しをしない)
▼コンポーネント
<div>
<p>test.blade.phpです。</p>
</div>
▼メインビュー
@component('components.test')
@endcomponent
・@component('コンポーネントファイル名')
- ファイル名はviewsからの絶対パスを記載。
- ディレクトリの中にある場合はディレクトリ名をドットで繋ぐ。
画面表示
comp-slot.blade.phpを開くと、コンポーネントの内容が表示された。

変数slotでデータを渡す。
次に、元のビューファイルの@component
の中に記載したデータを渡す方法について。
▼メインビュー
@component('components.test')
<p>コンポーネントの中身</p>
@endcomponent
@component
の中にある要素をコンポーネントに{{$slot}}
を記載することで好きな場所で呼び出すことができる。
▼コンポーネント
<div>
<p>test.blade.phpです。</p>
{{$slot}}
</div>
ブラウザの表示

▼複数呼び出す場合
<div>
{{$slot}}
<p>test.blade.phpです。</p>
{{$slot}}
</div>
ブラウザの表示

▼{{$slot}}
を呼び出さない{{$slot}}
を記述しない場合は、@component
内の記載は無視される。
▼コンポーネント
<div>
<p>test.blade.phpです。</p>
</div>

注意点
@component
の中身が@slot
などで分断して記述してある場合でも、@slot
を除いた、ひとまとまりの要素として出力される。
▼メインビュー
@component('components.test')
コンポーネントの中身(上)
@slot('xxx')
slotディレクティブのxxx
@endslot
コンポーネントの中身(下)
@endcomponent
▼コンポーネント
<div>
{{$slot}}
<p>test.blade.phpです。</p>
</div>

指定したslot名でデータを渡す
@component
内に複数のデータのまとまりを作成し、コンポーネントに渡すには、slot('スロット名')
を使う。
呼びだしは{{$スロット名}}
とする。
▼メインビュー
@component('components.test')
@slot('xxx')
slotディレクティブの中身
@endslot
@endcomponent
▼コンポーネント
<div>
{{$xxx}}
<p>test.blade.phpです。</p>
</div>

@slotを複数設置
ひとまとまりのデータを複数作成することができる。
▼メインビュー
@component('components.test')
<p>コンポーネントの中身</p>
@slot('xxx')
slotディレクティブの中身
@endslot
@endcomponent
▼コンポーネント
@component('components.test')
@slot('xxx')
slotディレクティブのxxx
@endslot
@slot('yyy')
slotディレクティブのyyy
@endslot
@endcomponent

まとめ
コンポーネントの中身を表示する方法を一つづつ確認すればだいぶわかりやすい。
1. コンポーネントの中身をそのまま表示
2. 変数slotでデータを渡す
3. 指定したslot名でデータを渡す
最後に、3つを複合すると以下のようなコードになる。
▼メインビュー
@component('components.test')
<p>コンポーネントの中身(上)</p>
@slot('xxx')
slotディレクティブのxxx
@endslot
@slot('yyy')
slotディレクティブのyyy
@endslot
<hr>
<p>コンポーネントの中身(下)</p>
@endcomponent
▼コンポーネント
<div>
{{$yyy}}
{{$slot}}
<p>test.blade.phpです。</p>
{{$xxx}}
{{$slot}}
</div>
