LoginSignup
3
5

More than 3 years have passed since last update.

Laravel Blade で extendsとincludeでyieldの挙動が変わる

Last updated at Posted at 2019-12-24

起きたこと

Laravel 6.6 (執筆時 最新版)のBladeファイルで、includeしたテーマのyield部分に、sectionが挿入されないことがあったのでメモ。

ファイル

こんなベースファイルに

base.blade.php
<!DOCTYPE html>
<head>
    @yield("head")
</head>

<body>
    @yield("body")
</body>
</html>

こんなheadタグのパーツを作って

head.blade.php
@section("head")
<title>@yield("title")</title>
@endsection

こんな実装bladeを作ったとする。

index.blade.php
@extends("base") // baseを継承

@include("head") // headをinclude

@section("title")  
index   //includeしたheadに、タイトル[index]を挿入
@endsection

@section("body")
body   //extendsしたbaseに、[body]を挿入
@endsection

これで生成されるhtmlは

<!DOCTYPE html>

<head>
<title></title>    <!-- タイトルが挿入されていない -->
</head>

<body>
body               <!-- bodyは挿入されている -->
</body>
</html>

このように、 @section("body") はきちんとyieldに挿入されるが @section("title") の部分は無視される。

思い通りの動き方のためには

index.blade.php
@extends("base")

// titleが挿入されるテンプレート head をincludeする前に
// section("title")を設定する
@section("title", "index")  

@include("head")

@section("body")
body
@endsection

このようにするとhead内のyieldにきちんと挿入される。

どうやら

  • extendsしたテンプレートへ挿入したいsectionはどこに書いても良い
    • extends宣言の前でも後でも良い
  • includeしたテンプレートへ挿入したいsectionは、includeするよりも先にsectionを書かないといけない
    • sectionの記述後にincludeしないといけない

といった制約がある様子。
どう日本語で表現したらいいのか難しいですが、多重yieldとか、includeしたテンプレートへのyieldとか、そういった感じでしょうか。

そのうちLaravelのコード直接読んで仕組みを理解したいところですが、今は覚書として。

3
5
0

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
3
5