Build layouts sử dụng Components:
Tạo layout component:
<!-- resources/views/components/layout.blade.php -->
<html>
<head>
<title>{{ $title ?? 'Todo Manager' }}</title>
</head>
<body>
<h1>Todos</h1>
<hr/>
{{ $slot }}
</body>
</html>Áp dụng layout:
Ví dụ tạo 1 view đơn giản hiển thị task list:
<!-- resources/views/tasks.blade.php -->
<x-layout>
@foreach ($tasks as $task)
{{ $task }}
@endforeach
</x-layout>Như vậy phần content trong view trên sẽ được cung cấp cho biến $slot ở trong layout component. Ở layout còn có biến $title nhận giá trị mặc định khi không truyền giá trị cho nó. Để inject title ta sử dụng cú pháp sau:
<!-- resources/views/tasks.blade.php -->
<x-layout>
<x-slot:title>
Custom Title
</x-slot>
@foreach ($tasks as $task)
{{ $task }}
@endforeach
</x-layout>Tạo Layout sử dụng thừa kế Template:
Định nghĩa layout:
<!-- resources/views/layouts/app.blade.php -->
<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
</body>
</html>Chỉ thị @section định nghĩa 1 section content, chỉ thị @yield sử dụng để hiển thị content của 1 section cho trước.
Extend Layout:
Khi tạo view con extend layout, sử dụng chỉ thị @extends. View con sử dụng @section để inject content. Như ví dụ trên, content của những section này sẽ được hiển thị trong layout sử dụng @yield:
<!-- resources/views/child.blade.php -->
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@parent
<p>This is appended to the master sidebar.</p>
@endsection
@section('content')
<p>This is my body content.</p>
@endsection