Custom Blade Directives: Vũ khí bí mật giúp View gọn gàng
Mặc dù Blade Components là giải pháp UI tốt, đôi khi bạn cần các lệnh nhỏ (Directives) tương tự như @if, @foreach thay vì phải đóng gói cả HTML component.
1. Bản chất của Blade Directive
Blade sẽ đọc cấu trúc file .blade.php và biên dịch thành PHP thuần được cache trong storage/framework/views. Do đó, mục tiêu của Directive là trả về đoạn chuỗi PHP tương ứng.
2. Đăng ký Blade Directive
Đăng ký Directive trong phương thức boot của App\Providers\AppServiceProvider.
Ví dụ 1: Xử lý định dạng tiền tệ (@money)
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Blade::directive('money', function ($expression) {
return "<?php echo number_format($expression, 0, ',', '.') . ' VNĐ'; ?>";
});
}
}
Sử dụng trong Blade:
<div class="price">
Giá sản phẩm: @money($product->price)
</div>
Kết quả khi render sẽ trở thành:
<?php echo number_format($product->price, 0, ',', '.') . ' VNĐ'; ?>
Ví dụ 2: Rút gọn việc kiểm tra quyền hạn (@role)
Tạo directive tùy chỉnh cho logic Authorization riêng của ứng dụng (trong trường hợp không dùng thư viện bổ sung).
Blade::directive('role', function ($expression) {
return "<?php if(auth()->check() && auth()->user()->hasRole($expression)): ?>";
});
Blade::directive('endrole', function () {
return "<?php endif; ?>";
});
Sử dụng:
@role('admin')
<a href="/admin/dashboard">Truy cập Admin</a>
@endrole
3. Custom If Statements (Blade::if)
Đôi khi việc ghép chuỗi PHP ở trên khá mệt đối với các logic điều kiện trả về boolean. Blade::if là giải pháp sạch hơn nhiều:
Blade::if('env', function ($environment) {
return app()->environment($environment);
});
Sử dụng:
@env('local')
<!-- Chỉ hiển thị logic debug ở Local -->
<script src="http://localhost:35729/livereload.js"></script>
@endenv
Bằng cách tạo các Custom Directives, lập trình viên frontend sẽ không cần viết mã PHP xử lý logic định dạng dữ liệu, view sẽ tập trung 100% vào hiển thị HTML đúng nghĩa.