【Laravel 5.6】assetの管理を@sectionと@stackのどちらを使うか?

環境

PHP 7.1
Laravel 5.6
Bladeテンプレート

目的

Laravelのbladeでテンプレートを作成していた時に、javascriptやcssなどの管理をどのようにするのかドキュメントを見てもよく分からなかったので、整理するために調査。

テンプレートの構成としては2階層か3階層のテンプレート構成で作ることが多いので、その2パターンで比較します。

2階層テンプレート

構成は以下を想定

app.blade.php
 index.blade.php

app.blade.php



    @section(‘section-scripts’)
      console.log('app-section-scripts');
    @show
    @stack(‘stack-scripts’)
  
  
    @yield(‘contents’)
  

index.blade.php

@extends(‘app’)
@section(‘section-scripts’)
  @parent
  console.log('index-section-scripts');
@endsection
@push(‘stack-scripts’)
  console.log('index-stack-scripts push');
@endpush
@prepend(‘stack-scripts’)
  console.log('index-stack-scripts prepend');
@endprepend

実行結果

予想通りの結果でした。まあ単純なので当たり前ですね。

app-section-scripts
index-section-scripts
index-stack-scripts prepend
index-stack-scripts push

3階層テンプレート

構成は以下を想定

app.blade.php └ index.blade.php

app.blade.php



    @section(‘section-scripts’)
      console.log('app-section-scripts');
    @show
    @stack(‘stack-scripts’)
  
  
    @yield(‘contents’)
  

layout.blade.php

@extends(‘app’)
@section(‘section-scripts’)
  @parent
  console.log('layout-section-scripts');
@endsection
@push(‘stack-scripts’)
  console.log('layout-stack-scripts push');
@endpush
@prepend(‘stack-scripts’)
  console.log('layout-stack-scripts prepend');
@endprepend

index.blade.php

@extends(‘layout’)
@section(‘section-scripts’)
  @parent
  console.log('index-section-scripts');
@endsection
@push(‘stack-scripts’)
  console.log('index-stack-scripts push');
@endpush
@prepend(‘stack-scripts’)
  console.log('index-stack-scripts prepend');
@endprepend

実行結果

自信ないけど私の予想。(2階層目と3階層目の@prependはどうなるんだ??)

app-section-scripts
layout-section-scripts
index-section-scripts
layout-stack-scripts prepend
index-stack-scripts prepend
layout-stack-scripts push
index-stack-scripts push

結果

app-section-scripts
layout-section-scripts
index-section-scripts
index-stack-scripts prepend
layout-stack-scripts prepend
index-stack-scripts push
layout-stack-scripts push

予想外の結果となりました。どうも3階層目のテンプレートから判定されて行ってるようです。
これ、どうコントロールするのが正しいのか誰か教えて!

結論

2階層テンプレートの場合は、@stackを使う方が管理しやすい。いちいち@parentを書く必要もないし。共通は、app.blade.phpに直接記載し、追加分をstackでコントロールする感じかな。

3階層テンプレートになると、@stackは希望する動作にはならないし、どのような順番になるのかがソースでは分からないので@sectionを使用する。

以上がベストかな。