Blade簡單介紹
在Laravel中,Blade是一個模板引擎,可以用來將PHP原始碼和HTML混合在一起,並且可以使用一些簡單的語法來處理資料,讓程式碼更加簡潔。
Blade基本語法
{{ }}
用於輸出變數,例如{{ $title }}
,此用法會自動把輸出的內容做HTML轉義,例如{{ $title }}
輸出<h1>title</h1>
會變成<h1>title</h1>
{!! !!}
而這語法不會做其他動作,直接輸出原始值,例如{!! $title !!}
@php
用於寫原生PHP,例如@php echo $title; @endphp
,也可以使用@php($title)
來簡化
@if
、@elseif
、@else
、@endif
用於處理if的情況,用法如下:
1 2 3 4 5 6 7
| @if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif
|
@include('blade')
用於引入其他blade檔案,例如@include('blade', ['title' => 'title'])
,第二個參數可以傳入變數
includeif('blade')
用於當blade檔案存在時才引入
@includeWhen($boolean, 'blade')
用於當$boolean為true時才引入
常見迴圈用法:
@for
、@foreach
、@forelse
、@while
用於處理迴圈的情況,用法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @for ($i = 0; $i < 10; $i++) The current value is {{ $i }} @endfor
@foreach ($users as $user) <p>This is user {{ $user->id }}</p> @endforeach
@forelse ($users as $user) <li>{{ $user->name }}</li> @empty <p>No users</p> @endforelse
@while (true) <p>Hello World!</p> @endwhile
@continue @break
$loop->index $loop->iteration $loop->remaining $loop->count $loop->first $loop->last $loop->depth $loop->parent
|
@csrf
用於處理csrf的情況,例如@csrf
@method('PUT')
用於處理form表單中需要使用GET、POST之外的方法時可定義用法使用,例如以下範例:
1 2 3 4
| <form action="/foo/bar" method="POST"> @method('PUT') @csrf </form>
|
常用layout用法:
@extends('blade')
用於繼承其他blade檔案
@section('title', 'title')
來定義區塊
@yield('title', 'default')
來輸出區塊
@parent
來繼承父區塊
@stack('scripts')
和@push('scripts')
用於處理區塊堆疊的情況,與@section
和@yield
不同的是,@stack
可以定義多個區塊
- 範例說明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| @extends('layouts.app')
@section('title', 'title')
@section('content') @parent <p>This is my body content.</p> @push('scripts') <script src="/example.js"></script> @endpush @endsection
<html> <head> <title>App Name - @yield('title')</title> </head> <body> @section('sidebar') This is the master sidebar. @endsection <div class="container"> @yield('content') </div> @stack('scripts') </body> </html>
// 輸出結果 <html> <head> <title>App Name - title</title> </head> <body> This is the master sidebar. <div class="container"> <p>This is my body content.</p> </div> <script src="/example.js"></script> </body> </html>
|
其餘常用用法:
@lang('message')
功能與{{ __('message') }}
相同,會自動html轉義,用於處理語系的情況,用法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| return [ 'welcome' => 'Welcome to our application' ];
return [ 'welcome' => '歡迎來到我們的應用程式' ];
@lang('messages.welcome')
|
@verbatim
用於處理不需要解析的情況,用法如下:
1 2 3 4 5 6
| @verbatim <div class="container"> Hello, {{ $name }}. </div> @endverbatim
|
@error('title')
用於處理錯誤訊息的情況,大多為驗證錯誤時會帶著快閃Session跳回上一頁並顯示錯誤訊息,用法如下:
1 2 3 4
| @error('system_error') <div class="alert alert-danger">{{ $message }}</div> @enderror
|
@dump($array)
用於處理輸出變數的情況,和var_dump
相同,但輸出內容更好看,用法如下:
@dd($array)
用於處理輸出變數的情況,輸出內容更詳細和好看但是會中斷程式,用法如下: