Bladeの@pushと@stackは、レイアウトテンプレートを使用する際に、子ビューから親レイアウトの特定の場所にコンテンツを追加するための機能です。
基本的な使い方を説明します:
// 親レイアウト(layouts/app.blade.php)
<!DOCTYPE html>
<html>
<head>
<title>アプリケーション</title>
</head>
<body>
@yield('content') // メインコンテンツ用
// ここにスクリプトを集める
@stack('scripts') // スクリプト用のスタック
</body>
</html>
// 子ビュー(child.blade.php)
@extends('layouts.app')
@section('content')
<h1>メインコンテンツ</h1>
@endsection
// このスクリプトは親レイアウトの@stackの位置に追加される
@push('scripts')
<script>
console.log('子ビューのスクリプト');
</script>
@endpush
実際のレンダリング結果:
<!DOCTYPE html>
<html>
<head>
<title>アプリケーション</title>
</head>
<body>
<h1>メインコンテンツ</h1>
<script>
console.log('子ビューのスクリプト');
</script>
</body>
</html>
特徴:
@push('scripts')
<script>console.log('1つ目');</script>
@endpush
@push('scripts')
<script>console.log('2つ目');</script>
@endpush
2. @prependを使用すると、スタックの先頭に追加
```php
@prepend('scripts')
<script>console.log('最初に実行');</script>
@endprepend
@if($condition)
@push('scripts')
<script>console.log('条件付きスクリプト');</script>
@endpush
@endif
よく使用されるケース:
// 実践的な例
// layouts/app.blade.php
<!DOCTYPE html>
<html>
<head>
<title>アプリケーション</title>
@stack('styles') // CSSのスタック
</head>
<body>
@yield('content')
// 基本のJavaScript
<script src="app.js"></script>
// 追加のスクリプト
@stack('scripts')
</body>
</html>
// pages/user.blade.php
@extends('layouts.app')
@push('styles')
<link rel="stylesheet" href="user.css">
@endpush
@section('content')
<h1>ユーザープロフィール</h1>
@endsection
@push('scripts')
<script src="user.js"></script>
@endpush
これにより、各ページで必要な特定のスクリプトやスタイルを、レイアウトの適切な位置に追加できます。