LoginSignup
114
104

More than 5 years have passed since last update.

もう忘れない。laravelの@yieldと@sectionの関係

Last updated at Posted at 2018-06-02

@yield@sectionの関係

@section(‘head’) ~ @endsectionが一つのブロックで、前述の@yield(‘head’)部分に追加される

覚え方

yieldのyは親の"や(y)"

元のコード

index.php
<DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ページタイトル</title>
<meta name="description" content="説明文">
<meta name="keywords">
<link href="/css/layouts.css" rel="stylesheet">
<link href="/css/pages.css" rel="stylesheet">
</head>
<body>
<header>
    ヘッダー
</header>
        <p>コンテンツ</p>
<footer>
    フッター
</footer>
</body>
</html>

上記の共通部分<head>,<header>,<footer>@yieldにして、別のファイルで管理する。

ベースとなるコード

共通コードとなる外部化したい部分を@yieldにした"親"ファイルを作成。

layouts/parent.blade.php
<DOCTYPE HTML>
<html lang="ja">
<head>
@yield('head')
</head>
<body>
@yield('header')
        <p>コンテンツ</p>
@yield('footer')
</body>
</html>

外部化した<head>部分はhead.blade.phpへ

head.blade.php
@extends('layouts.parent')
@section('head')
<meta charset="UTF-8">
<title>ページタイトル</title>
<meta name="description" content="説明文">
<meta name="keywords">
<link href="/css/layout.css" rel="stylesheet">
<link href="/css/page.css" rel="stylesheet">
@endsection

外部化した<header>部分はheader.blade.phpへ

@extends('layouts.parent')
@section('header')
<header>
    ヘッダー
</header>
@endsection

外部化した<footer>部分はfooter.blade.phpへ

@extends('layouts.parent')
@section('footer')
<footer>
    フッター
</footer>
@endsection

説明

@extends('layouts.parent')

これで親のファイルを継承しています。親と子を結びつけるチェーンのような感じでしょうか。

@section('head') ~ @endsection

この部分が親(@extends)の@yield部分に召喚されるトンネルとなります。トンネルなので入り口(@section)と出口(@endsection)が必要になります。

@yield('head')

子の@section('head') ~ @endsectionというトンネルを通す穴です。親(@extends)に記載します。穴はひとつなので、閉じる必要もなしで@yield('head')一つのみ。

参照

https://qiita.com/k-waragai/items/504457527b32e113a489
http://cly7796.net/wp/php/to-a-common-layout-in-blade-template-of-laravel/

114
104
1

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
114
104