Học Laravel – Bài 18: Blade (Phần 3)

Form trong Blade:

CSRF Field:

<form method="POST" action="/profile">
    @csrf
 
    ...
</form>

Method field:

<form action="/foo/bar" method="POST">
    @method('PUT')
 
    ...
</form>

Validation Errors:

<!-- /resources/views/post/create.blade.php -->
 
<label for="title">Post Title</label>
 
<input id="title"
    type="text"
    class="@error('title') is-invalid @enderror">
 
@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Bạn có thể dùng thêm chỉ thị @else:

<!-- /resources/views/auth.blade.php -->
 
<label for="email">Email address</label>
 
<input id="email"
    type="email"
    class="@error('email') is-invalid @else is-valid @enderror">

Bạn có thể pass tên của error bag làm tham số thứ 2 cho chỉ thị @error để truy xuất thông báo lỗi ở page có nhiều form:

<!-- /resources/views/auth.blade.php -->
 
<label for="email">Email address</label>
 
<input id="email"
    type="email"
    class="@error('email', 'login') is-invalid @enderror">
 
@error('email', 'login')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

Stacks trong Blade:

Blade cho phép push vào 1 stack đã đặt tên mà có thể được render ở bất kỳ vị trí nào của view hoặc layout khác. Điều này hữu ích trong việc chỉ định thư viện Javascript cần thiết cho view con:

@push('scripts')
    <script src="/example.js"></script>
@endpush

Nếu bạn muốn push content nếu 1 điều kiện cho trước bằng true, sử dụng @pushIf:

@pushIf($shouldPush, 'scripts')
    <script src="/example.js"></script>
@endPushIf

Bạn có thể push vào 1 stack bao nhiêu lần tùy ý. Để render stack, sử dụng chỉ thị @stack:

<head>
    <!-- Head Contents -->
 
    @stack('scripts')
</head>

Nếu bạn muốn thêm content vào đầu trước stack, sử dụng @prepend:

@push('scripts')
    This will be second...
@endpush
 
// Later...
 
@prepend('scripts')
    This will be first...
@endprepend

Service Injection:

Chỉ thị @inject sử dụng để truy xuất 1 service từ service container. Tham số đầu tiên là tên của biến service, tham số thứ 2 là class hoặc interface của service đó:

@inject('metrics', 'App\Services\MetricsService')
 
<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Render Inline Blade Templates:

Thi thoảng bạn muốn chuyển 1 blade template string thành 1 HTML. Sử dụng method render của facade Blade. Method này nhận tham số là blade template string và 1 mảng tùy chọn data cho template:

use Illuminate\Support\Facades\Blade;
 
return Blade::render('Hello, {{ $name }}', ['name' => 'Julian Bashir']);

Laravel render inline blade template bằng cách viết nó vào trong storage/framework/views. Nếu bạn muốn Laravel gỡ những file tạm thời này sau khi render, bạn có thể cung cấp tham số deleteCachedView cho method:

return Blade::render(
    'Hello, {{ $name }}',
    ['name' => 'Julian Bashir'],
    deleteCachedView: true
);

Extend Blade:

Blade cho phép bạn tạo chỉ thị riêng sử dụng directive method. Ví dụ sau tạo chỉ thị @datetime($var) trả về 1 instance của DateTime:

<?php
 
namespace App\Providers;
 
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
 
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // ...
    }
 
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Blade::directive('datetime', function (string $expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }
}

Chỉ thị này tương đương với:

<?php echo ($var)->format('m/d/Y H:i'); ?>

Nếu update logic của chỉ thị, bạn cần xóa cache Blade views bằng lệnh php artisan view:clear.

Custom echo Handlers:

Nếu bạn thử “echo” 1 object sử dụng Blade, method __toString của object sẽ được gọi. Method này là “magic method” của PHP. Tuy nhiên, thi thoảng bạn có thể không kiểm soát được method này của 1 class nhất định, ví dụ khi lớp thuộc về 1 thư viện thứ 3. Trong trường hợp này Blade cho phép bạn đăng ký 1 custom echo handler. Để thực hiện, gọi method stringable của Blade. Method này nhận 1 closure. Closure này sẽ type-hint kiểu của object mà chịu trách nhiệm render. Thông thường method stringable sẽ được gọi trong boot của AppServiceProvider:

use Illuminate\Support\Facades\Blade;
use Money\Money;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Blade::stringable(function (Money $money) {
        return $money->formatTo('en_GB');
    });
}

Tùy biến lệnh If:

Tạo 1 chỉ thị custom thường phức tạp hơn mức cần thiết, vì vậy Blade cung cấp Blade::if cho phép bạn nhanh chóng tạo 1 chỉ thị điều kiện sử dụng closure. Ví dụ, tạo 1 chỉ thị check cấu hình “disk” của ứng dụng. Chúng ta có thể làm như thế này trong boot của AppServiceProvider:

use Illuminate\Support\Facades\Blade;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Blade::if('disk', function (string $value) {
        return config('filesystems.default') === $value;
    });
}

Sử dụng trong template như sau:

@disk('local')
    <!-- The application is using the local disk... -->
@elsedisk('s3')
    <!-- The application is using the s3 disk... -->
@else
    <!-- The application is using some other disk... -->
@enddisk
 
@unlessdisk('local')
    <!-- The application is not using the local disk... -->
@enddisk

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *