1
0

More than 3 years have passed since last update.

Laravelのレイアウトエンジンを使う

Last updated at Posted at 2020-04-30

目次

Laravelの記事一覧は下記
PHPフレームワークLaravelの使い方

Laravelバージョン

動作確認はLaravel Framework 7.19.1で行っています

Laravelのレイアウト処理

Laravelのレイアウト処理について書いていきます
viewsフォルダ配下に作成したblade.phpファイルを組み合わせて1つのビューとして処理をするものです

前提条件

eclipseでLaravel開発環境を構築する。デバッグでブレークポイントをつけて止める。(WindowsもVagrantもdockerも)
本記事は上記が完了している前提で書かれています
プロジェクトの作成もapacheの設定も上記で行っています

Controllerにメソッド追加

(1) /sample/app/Http/Controllers/SampleController.phpにchildメソッドを追記
public function child()
{
$data = ['msgList' => ["msg1", "msg2"]];
return view('sample.child', $data);
}

(2) /sample/routes/web.phpに下記を追記
Route::get('sample/child', 'SampleController@child');

viewの作成

(1) /sample/resources/views/layoutフォルダ作成
(2) /sample/resources/views/layout/parent.blade.phpファイル作成

parent.blade.php
<html>
    <head>
        <title>@yield('title')</title>
    </head>
    <body>
        <ul>
            @section('menu')
            <li>共通メニュー1</li>
            <li>共通メニュー2</li>
            @show
        </ul>
        <div>
            @yield('content')
        </div>
    </body>
</html>

(3) /sample/resources/views/componentフォルダ作成
(4) /sample/resources/views/component/msgList.blade.phpファイル作成

msgList.blade.php
<div>{{ $msgTitle }}</div>
@foreach ($msgList as $msg)
    <div>{{ $msg }}</div>
@endforeach
{{ $addMsg }}

(5) /sample/resources/views/sample/child.blade.phpファイル作成

child.blade.php
{{-- resources/views/layout/parent.blade.phpを使うのでlayout.parentにする --}}
@extends('layout.parent')

{{-- parent.blade.phpの@yield('title')を置換する --}}
@section('title', 'Sample@tpl')

{{-- parent.blade.phpの@section('menu')から@showまでを置換する --}}
@section('menu')
    {{-- parent.blade.phpの@section('menu')から@showまでを描画する --}}
    @parent
    {{-- child.blade.php独自のメニューを描画する --}}
    <li>独自メニュー1</li>
    <li>独自メニュー2</li>
@endsection

{{-- parent.blade.phpの@yield('content')を置換する --}}
@section('content')
    <p>child.blade.phpのコンテンツ</p>

    {{-- resources/views/component/msgList.blade.phpを描画する --}}
    @component('component.msgList', ['msgTitle' => 'コンポーネントタイトル', 'msgList' => $msgList])
        @slot('addMsg')
            <div>addMsg1</div>
            <div>addMsg2</div>
        @endslot
    @endcomponent

    {{-- resources/views/component/msgList.blade.phpを描画する --}}
    @include('component.msgList', ['msgTitle' => 'インクルードタイトル', 'msgList' => $msgList, 'addMsg' => '<div>addMsg1</div><div>addMsg2</div>'])

@endsection

動作確認

http://localhost/laravelSample/sample/tpl

実行結果

● 共通メニュー1
● 共通メニュー2
● 独自メニュー1
● 独自メニュー2

child.blade.phpのコンテンツ

コンポーネントタイトル
msg1
msg2
addMsg1
addMsg2
インクルードタイトル
msg1
msg2
<div>addMsg1</div><div>addMsg2</div>
1
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
1
0