のぐそんブログ

暗いおじさんがシコシコ書くブログです。

bladeでのレイアウトメモ

bladeのテンプレートやコンポーネント機能を利用した、レイアウトの組み方のメモです。

@section,@yield

@section,@yieldを利用することでテンプレートを作成することができます。

使い方

@sectionはコンテンツ領域を定義する為に利用します。

@section(名前)
...表示内容
@endsection

@yield@sectionの内容を読み込むのに利用します。

@yield(名前)

◎layout/base.blade.php

<html>
    <head>
    </head>
    <body>
        <h1>@yield('title')</h1> 
    </body>
</html>

◎index.blade.php @extendで利用するテンプレートを継承します。

@extends('layouts.base')
@section('title','タイトル')

親のsectionを上書きする

◎layout/base.blade.php

親テンプレートで@sectionを利用する場合は、@endsectionの代わりに@showを利用します。

<html>
<head>
</head>
<body>
@section('overwrite')
    上書きされる!
@show
</body>
</html>

◎index.blade.php

@extends('layouts.base')
@section('overwrite')
    上書きします!
@endsection

親テンプレートの内容も残したい場合は、以下のように@parentを利用する。

◎index.blade.php

@extends('layouts.base')
@section('overwrite')
    @parent
    上書きします!
@endsection

表示

上書きされる!上書きします!

@component

汎用パーツを作成することができます。

◎components/footer.blade.php

<div>
    <footer>
        <nav>
            <ul>
                {{$msg_nav}}
            </ul>
        </nav>
    </footer>
</div>

◎index.blade.php

@slotを利用すると変数をcomponentに連携することができます。

@extends('layouts.base')
@component('components.footer')
    @slot('msg_nav')
        <li>ナビ1</li>
        <li>ナビ2</li>
        <li>ナビ3</li>
     @endslot
@endcomponent

表示

・ナビ1
・ナビ2
・ナビ3

@include

単純なビューの埋め込みの場合は@includeが便利です。

使い方

@include(テンプレート名,[...値])

◎components/footer.blade.php

<div>
<h1>{{$title}}</h1>
</div>

◎index.blade.php

@extends('layouts.base')
@include('components.message',['title'=>'タイトル'])

表示

タイトル