Học Laravel – Bài 17: Views

Giới thiệu Views trong Laravel:

Views lưu trữ trong thư mục resource/views. Views thường viết dưới dạng Blade, ví dụ file resource/views/greeting.blade.php:

Blade
Hello {{ $name }}

Trong route gọi view:

PHP
Route::get('/', function() {
    return view('greeting', ['name' => 'James']);
});

// or
return View::make('greeting', ['name' => 'James']);

Tạo & Render Views:

Lệnh tạo view:

php artisan make:view greeting

Thư mục view lồng vào nhau:

Dùng “.” để tham chiếu các view lồng vào nhau. Ví dụ: file view: resource/views/admin/profile.blade.php:

PHP
return view('admin.profile')

Tạo view sẵn đầu tiên:

Dùng method first để tạo view đầu tiên tồn tại trong 1 mảng view cho trước. Nó hữu ích nếu ứng dụng hoặc package cho phép view có thể customize hoặc ghi đè:

PHP
return View::first(['custom.admin', 'admin'], $data);

Xác định 1 view tồn tại hay không:

PHP
if (View::exists('emails.customer'))

Pass data to views:

return view('greetings', ['name' => 'Victoria']);

Cách khác: dùng with method:

PHP
return view('greeting')
        ->with('name', 'victoria')
        ->with('email', 'vic@vic.com');

Share data cho tất cả view:

Dùng method share. Thông thường gọi method share trong boot của service provider:

PHP
class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        View::share('key', 'value');
    }
}

View composers:

View composer là những hàm callback hoặc method của class được gọi khi 1 view được render. Nếu bạn có dữ liệu mà bạn muốn được liên kết tới view mỗi lần nó được render, view composer giúp bạn tổ chức những logic đó vào 1 file riêng. View composer hữu dụng khi cùng 1 view được return bởi nhiều route hoặc controller và luôn cần 1 data cụ thể.

Thông thường view composer được register trong service providers. Trong ví dụ này, chúng ta giả sử đã tạo 1 App\Provider\ViewServiceProvider. Chúng ta sẽ sử dụng method composer của View facade để register view composer. Laravel không có thư mục mặc định cho class dựa trên view composer. Bạn có thể tạo thư mục app/View/Composers để lưu trữ:

PHP
<?php
 
namespace App\Providers;
 
use App\View\Composers\ProfileComposer;
use Illuminate\Support\Facades;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
 
class ViewServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // ...
    }
 
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Using class based composers...
        Facades\View::composer('profile', ProfileComposer::class);
 
        // Using closure based composers...
        Facades\View::composer('welcome', function (View $view) {
            // ...
        });
 
        Facades\View::composer('dashboard', function (View $view) {
            // ...
        });
    }
}

Nếu bạn tạo 1 service provider để chứa view composer register, bạn cần add vào service provider trong providers array trong file cấu hình config/app.php.

Khi đã register composer, method compose trong ProfileComposer sẽ được thực thi mỗi khi view profile được render. Ví dụ composer class:

PHP
<?php
 
namespace App\View\Composers;
 
use App\Repositories\UserRepository;
use Illuminate\View\View;
 
class ProfileComposer
{
    /**
     * Create a new profile composer.
     */
    public function __construct(
        protected UserRepository $users,
    ) {}
 
    /**
     * Bind data to the view.
     */
    public function compose(View $view): void
    {
        $view->with('count', $this->users->count());
    }
}

Tất cả view composers được resolve bởi service container nên bạn có thể type-hint bất kỳ independencies bạn cần vào constructor của composer.

Attach Composer vào nhiều Views:

Sử dụng method composer với tham số đầu tiên là 1 array views:

use App\Views\Composers\MultiComposer;
use Illuminate\Support\Facades\View;
 
View::composer(
    ['profile', 'dashboard'],
    MultiComposer::class
);

Method composer chấp nhận ký tự * như 1 wildcard, cho phép attach composer vào tất cả views:

use Illuminate\Support\Facades;
use Illuminate\View\View;
 
Facades\View::composer('*', function (View $view) {
    // ...
});

View Creators:

View “creators” tương tự view composers, tuy nhiêu nó thực thi ngay sau khi view được khởi tạo, thay vì chờ cho đến khi view được render. Dùng method creator để tạo 1 view creator:

use App\View\Creators\ProfileCreator;
use Illuminate\Support\Facades\View;
 
View::creator('profile', ProfileCreator::class);

Tối ưu views:

Tăng tốc hiệu năng khi deployment:

ShellScript
php artisan view:cache

Clear view cache:

ShellScript
php artisan view:clear

Để 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 *