Table of Contents
What is layout?
Generally in web application the same layout is used in different pages. By defining the layout in a single blade template we can use it in the entire application. We will create the layout using “template inheritance”. For that we will follow the following steps.
Steps to build layouts using template inheritance
The steps to create layouts using template inheritance are as follows.
Step 1: Creating a get route
First we will create a route for http://<SITEURL>/view
Route::get('view', function(){
return view('child');
});
Step 2: Creating Basic layout
We will create a basic layout in resources/views/layouts.blade.php.
<html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@includeif('header')
@section('sidebar')
<p>This is the master sidebar.</p>
@show
<div class="container">
@yield('content')
</div>
@includeif('footer')
</body>
</html>
Step 3: Creating basic header layout
We will create a basic header layout in resources/views/header.blade.php.
<div class="header">Header Content</div>
Step 4: Creating basic footer layout
We will create a basic footer layout in resources/views/footer.blade.php.
<div class="footer">Footer Content</div>
The @section directive, defines a section of content.
The @yield directive is used to display the contents.
Step 5: Creating child page
We will now create a child view page in resources/views/child.blade.php that inherits the layout.
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@parent
This is appended to the master sidebar.
@endsection
@section('content')
This is body content.
@endsection
@extends directive specifies which layout the child view should inherit.
The sidebar section uses the @parent directive to append content to the layout’s sidebar.
The @parent directive will be replaced by the content of the layout when the view is rendered.
The @endsection directive will only define a section while @show will define and immediately yield the section.
Now in the browser HTML output of http://<SITEURL>/view would be:
<html>
<head>
<title>App Name - Page Title</title>
</head>
<body>
<div class="header">Header Content</div>
<p>This is the master sidebar.</p>
<p>This is appended to the master sidebar.</p>
<div class="container">
<p>This is body content.</p>
</div>
<div class="footer">Footer Content</div>
</body>
</html>
Reference: https://laravel.com/docs/10.x/blade