よくあるbladeの親テンプレートと子テンプレートの例です。
resources/views/layouts/master.blade.php
<html>
<head>
<title>Laravel | @yield('title', 'Home')</title>
</head>
<body>
<div id='container'>
@yield('content')
</div>
@section('footer')
<script src="app"></script>
@show
</body>
</html>
resources/views/dashboard.blade.php
@extends('layouts.master')
@section('title', 'Dashboard')
@include
<h1>Dashboard</h1>
@include('common.error', ['text' => 'エラー'])
...
@endsection
@section('footer')
@parent
<script src="dashboard.js"></script>
@endsection
resources/views/common/error.blade.php
<div class="alert alert-error">
{{ $text }}
...
</div>
@include と @yield と @section どれも指定の場所にコンテンツを挿入するという意味では同じような機能です。
@include()
@include は 継承ができません。
デフォルト値の設定もできません。
変数を渡すことができます。
@yield()
@yield は 継承ができません。
デフォルト値の設定ができます。
@section()
@section()〜@endsection は 継承することができます。
例にあるように @parent と書くと親テンプレートの @section() の内容が展開されます。
scriptの追加記述の他、サイドバーをページによって出し分け or 追加等をしたい場合にも便利に使えそうです。
ちなみに @section の閉じタグですが、親テンプレートの場合は @show で終わり、 子テンプレートの場合は @endsection もしくは @stop で終わります。間違えずに覚えて使い分けましょう。
まとめ
| タグ | 外部読み込み | 変数渡し | デフォルト値設定 | 継承 |
|---|---|---|---|---|
| @include | ○ | ○ | ☓ | ☓ |
| @yield | ○ | ☓ | ○ | ☓ |
| @section | ○ | ☓ | ○ | ○ |