0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel Bladeの @section と @push の違い整理

Posted at

ある時こんなレビューが

@section('js')でscript系が動かないときは、@push('JS')を利用してください。

フアっとした理解で利用はしていたが整理する。

前提:Bladeテンプレートの仕組み

Bladeは、Laravelが提供するテンプレートエンジン。
ビューをパーツごとに分けて再利用できるようにする

たとえば、共通レイアウトを1つだけ定義して、
各ページでは必要な部分だけ差し替えることができる。

1. @section@yield

構文の意味

  • @section('名前'):コンテンツを定義する
  • @yield('名前'):コンテンツを呼び出す(表示する)

例:レイアウトファイル(layouts/app.blade.php)

<!DOCTYPE html>
<html>
<head>
  <title>@yield('title')</title>
</head>
<body>
  <header>共通ヘッダー</header>

  <main>
    @yield('content')
  </main>

  <footer>共通フッター</footer>
</body>
</html>

例:子ビュー(home.blade.php)

@extends('layouts.app')

@section('title', 'ホームページ')

@section('content')
  <h1>Welcome Home!</h1>
  <p>ここがホームページです</p>
@endsection

結果イメージ

<!DOCTYPE html>
<html>
<head>
  <title>ホームページ</title>
</head>
<body>
  <header>共通ヘッダー</header>

  <main>
    <h1>Welcome Home!</h1>
    <p>ここがホームページです</p>
  </main>

  <footer>共通フッター</footer>
</body>
</html>

2. @push@stack

@push は、指定した場所に後からコードを追加するための仕組み。

@stack が「呼び出し側」。

例:レイアウトファイル(layouts/app.blade.php)

<!DOCTYPE html>
<html>
<head>
  <title>@yield('title')</title>
  @stack('styles')
</head>
<body>
  @yield('content')

  @stack('scripts')
</body>
</html>

例:子ビュー(home.blade.php)

@extends('layouts.app')

@section('title', 'ホーム')

@section('content')
  <h1>HOME</h1>
@endsection

@push('scripts')
  <script src="/js/home.js"></script>
@endpush

@push('styles')
  <link rel="stylesheet" href="/css/home.css">
@endpush

結果(実際にレンダリングされるHTML)

<!DOCTYPE html>
<html>
<head>
  <title>ホーム</title>
  <link rel="stylesheet" href="/css/home.css">
</head>
<body>
  <h1>HOME</h1>
  <script src="/js/home.js"></script>
</body>
</html>

ページごとに異なるスクリプトを読み込みたいとき

@push('scripts')
  <script src="/js/page-specific.js"></script>
@endpush

親レイアウトで @stack('scripts') を定義しておけば、
複数ページ分のスクリプトが自動的に結合される。

注意

@section は「置き換え」、@push は「追加」。

  • 同じ @push('scripts') を複数書くと、
    書いた順にすべて追加される(上書きされない)。

まとめる

構文 目的 動作
@section コンテンツを定義 親の @yield に差し込まれる
@yield 定義を表示 子の @section とセットで使用
@push コードを後から追加 複数箇所からの追加が可能
@stack 追加した内容を表示 headfooter などに配置
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?