【Laravel】テンプレートでビューを楽に作る
はじめに
ビューファイルを作成する時にテンプレートを利用することで簡単に全体の統一感を出すことができます。
では、説明していきます
テンプレートの使い方
まずベースとなるテンプレートの利用方法について説明します。
テンプレートファイルの作成
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')
titleにPage 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に変数を代入します。
以上で説明は終わりです。
