
Học Laravel 10 cơ bản: Blade Template
1. Blade là gì?
-
Blade là template engine tích hợp sẵn trong Laravel.
-
Giúp viết HTML kết hợp PHP dễ dàng.
-
Hỗ trợ layout, include, component, vòng lặp, điều kiện.
-
File Blade nằm trong thư mục:
resources/views/
→ đuôi.blade.php
.
Ví dụ: resources/views/welcome.blade.php
2. Tạo View đơn giản
Trong routes/web.php
:
Tạo file: resources/views/hello.blade.php
👉 Truy cập http://localhost:8000/hello
→ hiển thị: Xin chào Laravel!
3. Blade Syntax cơ bản
Hiển thị biến:
Escape HTML:
{{ $content }} {{-- Escape (an toàn) --}} {!! $content !!} {{-- In raw HTML --}}
Điều kiện:
@if($age >= 18) <p>Người lớn</p> @else <p>Trẻ em</p> @endif
Vòng lặp:
Kiểm tra biến tồn tại:
4. Layout & Section
Layout chính (master layout)
Tạo file: resources/views/layouts/app.blade.php
View con kế thừa layout
Tạo file: resources/views/home.blade.php
Route test:
👉 http://localhost:8000/home
→ hiển thị trong layout.
5. Include (tách file nhỏ)
Tạo resources/views/partials/nav.blade.php
:
Trong layout:
6. Blade Component
Laravel Blade hỗ trợ component tái sử dụng.
Tạo component:
Tạo 2 file:
-
app/View/Components/Alert.php
(logic) -
resources/views/components/alert.blade.php
(giao diện)
File alert.blade.php
:
Dùng trong view:
👉 Tái sử dụng nhiều lần mà không cần viết lại.
7. CSRF Token trong Form
Khi dùng form POST → Laravel yêu cầu CSRF token để chống tấn công.
👉 Nếu thiếu @csrf
→ sẽ bị lỗi 419 Page Expired
.
✅ Tổng kết
Trong bài này bạn đã học:
-
Tạo view với Blade.
-
Cú pháp Blade cơ bản (biến, điều kiện, vòng lặp).
-
Layout & Section.
-
Include file nhỏ.
-
Component Blade.
-
CSRF trong form.