0
0
Laravelframework~5 mins

Template inheritance (@extends, @section, @yield) in Laravel

Choose your learning style9 modes available
Introduction

Template inheritance helps you reuse common parts of your web pages easily. It saves time and keeps your code neat by sharing layouts.

When you want all pages on your website to share the same header and footer.
When you need to change the main layout once and have it update everywhere.
When building a website with many pages that have similar structure but different content.
When you want to organize your views to avoid repeating the same HTML code.
When you want to separate page-specific content from the overall page design.
Syntax
Laravel
@extends('layout')

@section('sectionName')
  Content here
@endsection

@yield('sectionName')

@extends tells the view which layout to use as the base.

@section defines a part of the page content that fills a placeholder.

Examples
This view uses the 'master' layout and fills the 'title' and 'content' sections.
Laravel
@extends('master')

@section('title')
  Home Page
@endsection

@section('content')
  Welcome to the home page!
@endsection
The master layout defines placeholders for 'title' and 'content' that child views fill.
Laravel
<!-- In master.blade.php -->
<html>
<head>
  <title>@yield('title')</title>
</head>
<body>
  @yield('content')
</body>
</html>
Sample Program

The master.blade.php file is the main layout with placeholders for title and content. The home.blade.php file extends this layout and fills those placeholders with page-specific content.

Laravel
<!-- resources/views/layouts/master.blade.php -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@yield('title')</title>
</head>
<body>
  <header>
    <h1>My Website</h1>
  </header>

  <main>
    @yield('content')
  </main>

  <footer>
    <p>Ā© 2024 My Website</p>
  </footer>
</body>
</html>


<!-- resources/views/home.blade.php -->
@extends('layouts.master')

@section('title')
Home Page
@endsection

@section('content')
<p>Welcome to the home page!</p>
@endsection
OutputSuccess
Important Notes

Always name your sections clearly to avoid confusion.

You can have multiple @section blocks in one view.

If a section is not defined in the child view, the @yield in the layout will be empty.

Summary

Template inheritance lets you build a base layout and fill parts of it in child views.

Use @extends to pick the base layout, @section to add content, and @yield to show it.

This keeps your code DRY (Don't Repeat Yourself) and easy to maintain.