LoginSignup
51
54

More than 5 years have passed since last update.

Bladeの構文をざっくりと

Posted at

Laravel標準のテンプレートエンジンであるbladeについてざっくりと構文紹介

値の表示

HTMLエスケープを行う

{{ $value }}

HTMLエスケープを行わない

{!! $value !!}

どちらも波括弧内が評価されてから表示される

制御文

if

@if(condition1)
...
@elseif(condition2)

@else

@endif

unless

@ifと逆の働きをする

@unless(condition)
...
@else

@endunless

isset

$variableが定義されていた場合にtrueとなる.

@isset($variable)
...
@else

@endisset

empty

$variableが空文字列, null, 0などの時にtrueとなる

@empty($variable)
...
@else

@endempty

注)issetとemptyは内部的にPHPのisset, emptyが使われる。両者の使い方は非常に癖があるので(特にempty)、PHP isset, empty, is_null の違い早見表が参考になる。

for

@for(initialize; condition; increment)
...
@endfor

foreach

@foreach($array as $variable)
...
@endforeach

foreach-else

$arrayから取り出す値が無くなったら@emptyの処理を実行して終了する。

@forelse($array as $variable)
...
@empty
...
@endforelse

while

@while(condition)
...
@endwhile

break, continue

@break
@continue

php

PHPのコードを直接書ける。やたらめったら使うものではない。

@php
...
@endphp

$loopについて

@foreachなどの繰り返しディレクティブの中では$loopという特殊変数が利用できる。このオブジェクトはループに関する情報を保持している。

プロパティ名 意味
index ループの現在のインデックス(0スタート)
iteration 現在の繰り返し回数(1スタート)
remaining 残りループ回数
first 最初の繰り返しならtrue
last 最後の繰り返しならtrue
depth ループのネスト数
parent ネストしている場合、上位にあるループの$loop

以下サンプル

@foreach($data as $d)
    @if($loop->first)
        <h3>list</h3>
    @endif
    no.{{$loop->iteration}}: {{$d}}<br>
@endforeach
51
54
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
51
54