
Template Inheritance in Laravel
Template inheritance in Laravel is achieved through the use of Blade, Laravel’s templating engine. Blade allows you to define a master or parent template that contains the common structure of your web pages, and then you can extend or inherit from this master template in your child views, which only need to define the unique content specific to each page. This approach helps maintain a consistent layout across your application and reduces code duplication.
Here’s how template inheritance works in Laravel using Blade:
1. Create a Master Layout (Parent Template):
In Laravel, a master layout is typically created as a Blade view. This view defines the common structure of your web pages, including headers, footers, navigation menus, and any other elements that are consistent across multiple pages. For example, you can create a file named master.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
<header>
<!-- Header content -->
</header>
<nav>
<!-- Navigation menu -->
</nav>
<main>
@yield('content')
</main>
<footer>
<!-- Footer content -->
</footer>
</body>
</html>
In the master layout, notice the use of @yield('sectionName')
directives. These placeholders will be replaced with content from the child views.
2. Create Child Views:
Child views extend the master layout and provide specific content for each page. For example, you can create a file named home.blade.php
:
@extends('master')
@section('title', 'Home Page')
@section('content')
<h1>Welcome to the Home Page</h1>
<p>This is the content of the home page.</p>
@endsection
In the child view, you use the @extends('master')
directive to indicate that it extends the master.blade.php
layout. You can then use the @section('sectionName')
directive to define content that will replace the placeholders defined in the master layout.
3. Rendering the View:
To render a view that extends a master layout, you can use Laravel’s view
function in your controller method:
public function home()
{
return view('home');
}
In this example, the home
method returns the home.blade.php
view, which extends the master.blade.php
layout.
4. Output:
When you access the “home” page in your browser, Laravel will render the home.blade.php
view, inheriting the structure defined in the master.blade.php
layout. The @yield
directives in the master layout will be replaced with the content defined in the child view.
This way, you can maintain a consistent layout for your web application while easily customizing the content of each page by creating child views that extend the master layout.