6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelのBladeで親-子-孫のレイアウトを実現するための簡単なやり方

Posted at

概要

Laravelのbladeを利用して、3階層にレイアウトを振りたいときがあります。

例えば、タブを切り替えたいんだけど、viewを分けなきゃいけない・・・。でもタブの部分とかは共通だからviewに毎回書くのは面倒・・・というときです。
例として上げるとすれば食べログの詳細ページのように、メニューなどに移動するとしても上部は共通レイアウトですよね。こんなとき、マスターのレイアウトをもう一個作るというのもありですがそれはそれでレイアウトに重複する部分が出てきてしまって更新時にミスが起こりやすくなります。

想定

本来、以下の場合に

master.blade.php
header
@yield('content')
footer
sublayout.blade.php
@extends('master')
@section('content')
   aaa
   @yield('content')
   bbb
@endsection←か@stop
show.blade.php
@extends('sublayout')
@section('content')
    ccc
@endsection

以下のような結果として出てほしいわけです。

header
aaa
ccc
bbb
footer

ただこのソースの場合だと以下の結果になります。

header
ccc
footer

sublayoutのsectionが意味を成してないことになってますね。

解決方法

endsectionをoverwriteに変更すれば解決します。

なんで直感的にならなかったのかは歴史的な背景があり、

このissueで話されています。
端的に言えば5.1の時点でoverwriteじゃなかったから移せなかった。ってことですね。

そのうちこの仕様は変わるのかもですが・・・。

強引に切り替える

こういうのを入れれば良いですね。

\Blade::directive('endsection', function () {
    return '<?php $__env->stopSection(true); ?>';
});
6
3
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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?