Laravel Frontend - fantasy0107/notes GitHub Wiki

Blade Templates

樣板引擎
所有的 blade 都會被編譯成純 PHP code
.blade.php
儲存在 resources/views

template 繼承

定義 Layout

使用 blade 的好處 inheritance 和 sections

<!-- Stored in resources/views/layouts/app.blade.php -->

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

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

擴展 Layout

@extends 會指出那些 child view 需要被繼承
@yield => 需要被繼承
@section => 繼承的內容 <-----> @endsection @parent

// 呼叫 view
Route::get('blade', function () {
    return view('child');
});

Components & Slots

<!-- /resources/views/alert.blade.php -->

<div class="alert alert-danger">
    {{ $slot }}
</div>
@component('alert')
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

Displaying Data

Route::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});

// in welcome
Hello, {{ $name }}.

//可以在 blade 使用 php function
The current UNIX timestamp is {{ time() }}.

// {{ }} 會自動送到 htmlspecialchars 去避免 XSS 攻擊 

// 不想 escape 可以用
Hello, {!! $name !!}.

Rendering JSON

// 陣列變成 json 

<script>
    var app = @json($array);
</script>

傳Data 給 Blade

key name 會是 blade 的 variable name

//Route or controller
Route::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});

//blade
Hello, {{ $name }}.

在blade 中的 {{ }} 會避免掉 XSS attacks 用的是 htmlspecialchars function

Control Structures

if

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@isset($records)
    // $records is defined and is not null...
@endisset

@empty($records)
    // $records is "empty"...
@endempty

Authentication Directives

@auth
    // The user is authenticated...
@endauth

@guest
    // The user is not authenticated...
@endguest

Switch

switch($i)
    @case(1)
        First case...
        @break

    @case(2)
        Second case...
        @break

    @default
        Default case...
@endswitch

for

@for ($i = 0; $i < 10; $i++)
    The current value is {{ $i }}
@endfor 

foreach

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

Comments

{{-- This comment will not be present in the rendered HTML --}}

Including Sub-Views

<div>
    @include('shared.errors')

    <form>
        <!-- Form Contents -->
    </form>
</div>

//帶參數
@include('view.name', ['some' => 'data'])

Stacks

Service Injection

// retrieve a service from the Laravel service container

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Extending Blade

Frontend Scaffolding

//切換成用 react laravel 5.5後可用

php artisan preset react

npm install
⚠️ **GitHub.com Fallback** ⚠️