Laravel Blade Templates

Laravel Blade Templates

Is the simple, yet powerful templating engine provided with Laravel.

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

Does not restrict you from using plain PHP code in your views.

Extending Blade

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Template Inheritance

Components & Slots

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

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

<div class="alert alert-danger">
    <div class="alert-title">{{ $title }}</div>

    {{ $slot }}
</div>
@component('alert')
    @slot('title')
        Forbidden
    @endslot

    You are not allowed to access this resource!
@endcomponent

Provide similar benefits to sections and layouts.

Displaying Data

Route::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});
Hello, {{ $name }}
The current UNIX timestamp is {{ time() }}

Control Structures

Forms

Including Sub-Views

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

    <form>
        <!-- Form Contents -->
    </form>
</div>
@include('view.name', ['some' => 'data'])
@includeIf('view.name', ['some' => 'data'])
@includeWhen($boolean, 'view.name', ['some' => 'data'])
@includeFirst(['custom.admin', 'admin'], ['some' => 'data'])

Stacks

@push('scripts')
    <script src="https://laravel.com/example.js"></script>
@endpush
<head>
    <!-- Head Contents -->

    @stack('scripts')
</head>
@push('scripts')
    This will be second...
@endpush

// Later...

@prepend('scripts')
    This will be first...
@endprepend

You may push to a stack as many times as needed.

Service Injection

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

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

Laravel Blade Templates — Structure map

Clickable & Draggable!

Laravel Blade Templates — Related pages: