Get in touch
or send us a question?
CONTACT

[Laravel Tutorials] – Bài 6: View – Blade (phần 1)

Views là gì?

Views là nơi hiển thị những gì chúng ta thấy trên trình duyệt, phần lớn có cấu trúc HTML

Trong Laravel, View sử dụng cấu trúc Blade Template, nên tên file sẽ là {name}.blade.php và chứa trong thư mục resources/views

Trong Views có thể sử dụng tất cả các ngôn ngữ mà PHP hỗ trợ như: HTML, JS, CSS, PHP,…

Tạo View trong Laravel

Trong thư mục resources/views tạo một file có tên hello-world.blade.php có nội dung như sau:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Hello - World</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

Gọi View trong Laravel

Cú pháp gọi view trong Laravel như sau:

view($viewname, $data);

Ví dụ gọi view trong Route:

Route::get('/hello-world', function () {
    return view('/hello-world');
});

Kết quả:

Các cách truyền dữ liệu cho View

Sử dụng Mảng

view($viewname, ['key' => 'value']);

Ví dụ:

Route::get('product/{productId}', function ($productId) {
    return view('product', ['productId' => $productId]);
});

Sử dụng with()

view($viewname)->with('key', 'value');

Ví dụ:



Route::get('product/{productId}', function ($productId) {
    return view('product')->with('productId', $productId);
});

Sử dụng compact()

compact('variable1', 'variable2', ...)

Ví dụ:

Route::get('product/{productId}', function ($productId) {
    return view('product', compact('productId'));
});

Lời kết

Trong bài này mình chỉ nói đến khái niệm và các cách truyền data vào view trong Laravel. Phần sau mình sẽ giới thiệu chi tiết về Blade Template trong Laravel.

Leave a Reply

Your email address will not be published. Required fields are marked *