4.

【Laravel】個別のページ(Bladeテンプレート)にcssやjsを反映させる方法

編集
この記事の要点
  • Laravel Blade で特定ページにだけ CSS / JS を読み込む方法
  • レイアウトに @stack / @section プレースホルダを定義
  • 個別 view から @push / @section で追加
  • 一般的に @stack('styles') / @stack('scripts') 前に配置
  • 優先度の高い順 (e.g. Bootstrap → カスタム) で出力されるよう書く

 

方法 1: @stack / @push(推奨)

同じプレースホルダに複数箇所から追加できる「stack」を使う方法。

レイアウト側





    @yield('title')

    
    

    
    @stack('styles')


    @yield('content')

    
    

    
    @stack('scripts')

個別ページ側


@extends('layouts.app')

@section('title', 'ユーザー一覧')

@push('styles')
    
    
@endpush

@section('content')
    

ユーザー一覧

@foreach ($users as $user)
{{ $user->name }}
@endforeach
@endsection @push('scripts') @endpush

方法 2: @section / @yield

1 箇所からの挿入のみ (上書き) で十分なケース。



    
    @yield('styles')


    @yield('content')
    
    @yield('scripts')



@extends('layouts.app')

@section('styles')
    
@endsection

@section('content')
    ...
@endsection

@section('scripts')
    
@endsection

@push vs @section の使い分け

項目@stack / @push@yield / @section
挿入箇所複数 view から追加可能1 つの section を 1 つの view が定義
順序追加順(先 → 後)1 つだけ
用途レイアウト + コンポーネント両方から script 追加ページ固有の単一 CSS / JS
パーシャル / コンポーネント内から使える○ @push× (@yield は section 1 つに限定)

@once で重複防止

パーシャル (含めるパーツ) を複数回 include しても、CSS / JS は 1 回だけ読み込みたい:


@once
    @push('styles')
        
    @endpush
    @push('scripts')
        
    @endpush
@endonce




@include('partials.datepicker')
@include('partials.datepicker')
@include('partials.datepicker')

@prepend (先頭に追加)

後から追加するけど stack の先頭に置きたい(jQuery より先に Polyfill 等):

@prepend('scripts')
    
@endprepend

Vite との統合

Laravel 10+ はデフォルトで Vite を使う:



    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @stack('styles')


    @yield('content')
    @stack('scripts')



@push('styles')
    @vite(['resources/css/users.css'])
@endpush

@push('scripts')
    @vite(['resources/js/users.js'])
@endpush

# Vite が hot reload + バンドル + cache busting を自動化

条件付き読み込み

@push('scripts')
    @if (auth()->check())
        
    @endif

    @env('production')
        
    @endenv

    @if (config('app.feature.chat'))
        
    @endif
@endpush

パフォーマンスの考慮

  • defer / async: @endpush @push('styles') @endpush

    関連記事

    編集
    Post Share
    子ページ

    子ページはありません

    同階層のページ
    1. 親ビューと子ビュー(@section, @yield, @extends, @parent, @include)
    2. 条件分岐(@if)
    3. 繰り返し(@for, @foreach, @forelse, @while)
    4. 個別のページにcssやjsを反映させる方法