Template inheritance is a powerful feature provided by Laravel's Blade templating engine, allowing you to define a master layout and extend it in other views. This helps in creating consistent layouts across your application and reduces redundancy in code.
Create a master layout file that contains the common structure and elements of your application layout. Typically, this file is named something like app.blade.php
and is stored in the resources/views/layouts
directory.
Example of resources/views/layouts/app.blade.php
:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@yield('title', 'Your App Title')</title>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
In your other Blade views, you can extend the master layout using the @extends
directive and provide content for specific sections using @section
and @endsection
directives.
Example of resources/views/welcome.blade.php
:
@extends('layouts.app')
@section('title', 'Welcome Page')
@section('content')
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card mt-5">
<div class="card-header">
<h5 class="card-title">Welcome to Your Application</h5>
</div>
<div class="card-body">
<p class="card-text">This is the content of your welcome page.</p>
</div>
</div>
</div>
</div>
@endsection
In your master layout (app.blade.php
), you can define additional sections that child views can optionally override. Use the @yield
directive to define these sections.
Example:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<!-- Head content here -->
<title>@yield('title', 'Your App Title')</title>
<!-- More head content -->
</head>
<body>
<div class="container">
@yield('content')
</div>
@section('footer')
<!-- Footer content here -->
@show
</body>
</html>
In child views, you can override the footer
section by redefining it within a @section('footer') ... @endsection
block.
You can include reusable partial views within your Blade templates using the @include
directive. This helps in keeping your views modular and maintaining separation of concerns.
Example:
@extends('layouts.app')
@section('title', 'Welcome Page')
@section('content')
@include('partials.header')
<div class="row">
<div class="col-md-6 offset-md-3">
<!-- Main content here -->
</div>
</div>
@include('partials.footer')
@endsection
That's the basic idea of template inheritance in Laravel Blade. It helps you create modular and reusable views while maintaining a consistent layout across your application.