LoginSignup
187
187

More than 3 years have passed since last update.

Laravel Blade で@include @yield @section を使いこなそう

Last updated at Posted at 2017-01-02

よくある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
187
187
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
187
187