9
6

More than 3 years have passed since last update.

【Laravel】テンプレートでビューを楽に作る

Posted at

はじめに

ビューファイルを作成する時にテンプレートを利用することで簡単に全体の統一感を出すことができます。
では、説明していきます

テンプレートの使い方

まずベースとなるテンプレートの利用方法について説明します。

テンプレートファイルの作成

layoutsフォルダの中にapp.blade.phpのファイルを作成してください。
そして、下記の内容を記述してください。

resources/views/layouts/app.blade.php
<html>
    <head>
        <title>アプリ名 - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            ここがメインのサイドバー
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

@section
  使用目的はコンテンツの区画を定義することです。
  最後には@showを使用します。
  @section('sidebar')記述でsidebarという区画を定義しています。
@yield
  表示内容を定義するためのものです。値を表示する場所を指定します。
  @yield('title')titleという変数を使う場所を指定しています。

ビューファイルの編集

ビューファイルでのレイアウトの参照方法について説明します。

resources/views/child.blade.php
@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @@parent

    <p>ここはメインのサイドバーに追加される</p>
@endsection

@section('content')
    <p>ここが本文のコンテンツ</p>
@endsection

@extends

@extends('layouts.app')
  layouts/app.blade.phpを継承します。

@section

@section('title', 'Page Title')
  titlePage Titleを代入する

@section

@section('sidebar')
    @@parent
    <p>ここはメインのサイドバーに追加される</p>
@endsection

@section('sidebar')sidebarに代入する値を設定します。
@@parentは継承元のapp.blade.phpの内容を表しています。
@endsection@sectionの終わりです。

コンポーネントの使い方

コンポーネントとは部分的に使うテンプレートです。

resources/views/alert.blade.php
<div class="alert alert-danger">
    <div class="alert-title">{{ $title }}</div>
    {{ $slot }}
</div>

$slotには下記の@component内の@slot以外の内容が入ります。

ビューファイルでのコンポーネントの参照方法を説明します。

resources/views/child.blade.php
@component('alert')
    @slot('title')
        Forbidden
    @endslot
    You are not allowed to access this resource!
@endcomponent

@component('alert')alert.blade.phpを参照します。
@slot('title')$titleに変数を代入します。

以上で説明は終わりです。

疑問、気になるところがございましたら、質問、コメントよろしくお願いします!!!

9
6
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
9
6