yieldを使用した例
一般的なのは@yield
を使用する方法です。
例えばtitle
やdescription
を設定したい場合レイアウトレンプレートは下記のように記述します。
resources/views/layouts/app.blade.php
- <head>
- <title>@yield('title') - サイトタイトル</title>
- <meta name="description" content="@yield('description')">
- </head>
- <body>
- @yield('content')
- </body>
子のテンプレートでは@section
ディレクティブで設定します。
メインコンテンツのような長いもは@section
から@endsection
で囲みます。
タイトルのように変数的に使用する場合は@section
の第二引数で指定します。
resources/views/page.blade.php
- @extends('layouts.app')
- @section('title', 'ページタイトル')
- @section('description', 'ページ概要')
- @section('content')
- コンテンツ
- @endsection
変数を使用した例
ただ表示するだけだったらyieldで良いのですが、分岐させて表示させたい場合があります。
たとえばタイトルタグはトップページにはサイトタイトルのみ表示して、下層はサイトタイトルとページタイトルの間に「-」とかを付けたいとかあると思います。
これは多分yieldではできないっぽいので変数を使います。
resources/views/layouts/app.blade.php
- <head>
- <title>@isset($title){{ $title }} - @endissetサイトタイトル</title>
- <meta name="description" content="{{ $description or 'サイト概要' }}">
- </head>
- <body>
- @yield('content')
- </body>
変数は普通に<?php ?>
で囲んで指定できますが、@php @endphp
の方がBladeっぽいですね。
resources/views/page.blade.php
- @php
- $title = 'ページタイトル';
- $description = 'ページ概要';
- @endphp
- @extends('layouts.app')
- @section('content')
- コンテンツ
- @endsection
ということで普通に変数使えるんだということでした。