1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Bladeの記述を学ぶ【Laravel8】

Posted at

業務でBladeを書く機会があったのでメモします。

if文

@php
    $name= '太郎'
@endphp

<!-- 表示の条件分岐 -->
@if($name === '太郎')
    <p>おはよう{{ $name }}</p>
@elseif($name === '次郎')
    <p>こんにちは{{ $name }}</p>
@else
    <p>こんばんは{{ $name }}</p>
@endif

変数をテンプレートに表示させるには{{ }}を使います。

foreach

配列

@php
    $names = ['太郎','次郎','三郎']
@endphp

@foreach ($names as $name)
    <p>こんにちは{{ $name }}</p>
@endforeach

二次元配列

@php 
  $reviews = [
    ['良い','普通','悪い'],
    ['good','usually','bad'],
  ]
@endphp

@foreach ($reviews as $review)
    @foreach ($review as $val)
        <p>{{ $val }}です</p>
    @endforeach
@endforeach

foreachをネストすることで表示。

連想配列

@php
    $names = [
    '番号' => 1,
    '名前' => '太郎',
    '年齢' => 30
    ];
@endphp

@foreach ($names as $key => $val)
    <p>{{ $key }}{{ $val }}です</p>
@endforeach

・連想配列を定義する際は、=>(ダブルアロー)を使います。
・foreachでキーと値を両方取得したい場合も、=>を使うことで取得できます。

他のBladeの読み込み

@includeを使って、別のbladeを読み込む。
これを使えばコンポーネント毎の記述もできます。

parent.blade.php
<h1 class="title">
  コンテンツ
</h1>

<div class="container">
  @include('child')
  {{-- 同階層のchild.blade.phpを取り込み --}}
</div>

child.blade.php
<p>コンテンツ1</p>

includeのループ

子bladeをループさせることもできます。

parent.blade.php
@php
    $count = 5;
@endphp

<h1 class="title">
  コンテンツ
</h1>

<div class="container">
  @for ($i = 0; $i < $count; $i++)
    @include('child')
  @endfor
</div>

共通レイアウトを使う

共通デザインで中身だけ動的に切り替えたい場合、以下の様な記述ができます。

親(共通テンプレート)

app.blade.php
<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  {{-- @yieldで子のコンテンツを表示させる --}}
  <title>@yield("title")</title>
</head>

<body>
  <main class="main">
    {{-- @yieldで子のコンテンツを表示させる --}}
    @yield("contents")
  </main>
</body>
</html>

contents.blade.php
{{-- 共通のレイアウトを指定する --}}
@extends('layouts.app')

{{-- titleの値 --}}
@section('title','TOPページ')

{{-- contentsの値 --}}
@section('contents')
<div class='content'>
  <p>見出し</p>
  <p>内容・内容</p>
</div>
@endsection

@extendsで共通で使いたい親bladeを指定します。

@sectionを使って、親のテンプレートに繋ぎ込む値を設定し、

@yieldを記述した場所に、@sectionで定義した値を格納しています。

まとめ

普段Vueを使っているんですが、似たような記述ができました。
また思ったよりもシンプルなので使いやすく感じました。
他にも便利な記述があったら追加していきます!

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?