0
0
Laravelframework~15 mins

Template inheritance (@extends, @section, @yield) in Laravel - Deep Dive

Choose your learning style9 modes available
Overview - Template inheritance (@extends, @section, @yield)
What is it?
Template inheritance in Laravel Blade allows you to create a base layout and then build other pages by extending this layout. You define sections in the base template that child templates can fill with their own content. This helps keep your HTML organized and avoids repeating the same code on every page.
Why it matters
Without template inheritance, you would have to copy and paste the same HTML structure on every page, making your code hard to maintain and update. Template inheritance saves time, reduces errors, and makes your website easier to change because you only update the base layout once.
Where it fits
Before learning template inheritance, you should understand basic Blade syntax and how Laravel views work. After mastering this, you can learn about Blade components and slots for even more flexible templates.
Mental Model
Core Idea
Template inheritance lets you build a main page skeleton and fill in parts of it on different pages, so you write shared layout once and customize only what changes.
Think of it like...
It's like having a reusable cake mold (base layout) where you bake cakes (pages) by adding different toppings (sections) each time without making a new mold.
┌─────────────────────────────┐
│        Base Layout          │
│ ┌───────────────┐           │
│ │ Header        │           │
│ ├───────────────┤           │
│ │ @yield('body')│ <--- Slot │
│ ├───────────────┤           │
│ │ Footer        │           │
└─┴───────────────────────────┘
          ▲
          │
┌─────────────────────────────┐
│      Child Template         │
│ @extends('base')            │
│ @section('body')            │
│   Custom page content here  │
│ @endsection                 │
└─────────────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Blade Templates
🤔
Concept: Learn what Blade templates are and how Laravel uses them to render HTML.
Blade is Laravel's simple templating engine. It lets you write HTML mixed with special Blade syntax to create dynamic pages. Each Blade file ends with .blade.php and can include variables and control structures.
Result
You can create a basic view file that Laravel can render with dynamic content.
Understanding Blade templates is the first step to using Laravel's powerful view system effectively.
2
FoundationCreating a Base Layout
🤔
Concept: Learn how to create a base layout that other templates can reuse.
A base layout is a Blade file that contains the common HTML structure like header, footer, and main content area. Use @yield('sectionName') to mark where child templates can insert content.
Result
You have a reusable layout file with placeholders for content.
Creating a base layout prevents repeating the same HTML on every page and centralizes your design.
3
IntermediateUsing @extends to Inherit Layouts
🤔Before reading on: Do you think @extends replaces the entire base layout or just adds to it? Commit to your answer.
Concept: Learn how child templates inherit the base layout using @extends directive.
In a child Blade file, use @extends('base') at the top to tell Laravel this template uses the 'base' layout. This means the child will fill in the sections defined by @yield in the base.
Result
Child templates share the base layout structure automatically.
Knowing that @extends links child templates to the base layout helps you organize your views cleanly.
4
IntermediateDefining Content with @section
🤔Before reading on: Does @section content replace or append to the base layout's @yield? Commit to your answer.
Concept: Learn how to fill the placeholders in the base layout using @section in child templates.
Inside the child template, use @section('sectionName') to start content for that section, and @endsection to end it. This content replaces the corresponding @yield in the base layout when rendered.
Result
The base layout's placeholders show the child template's content.
Understanding @section lets you customize parts of the layout without rewriting the whole page.
5
IntermediateDisplaying Sections with @yield
🤔
Concept: Learn how the base layout uses @yield to show content from child templates.
@yield('sectionName') in the base layout is a placeholder. When Laravel renders the page, it replaces @yield with the content from the child template's matching @section.
Result
The final rendered page combines base layout and child content seamlessly.
Knowing @yield is the insertion point clarifies how template inheritance stitches pages together.
6
AdvancedNested Sections and Stacks
🤔Before reading on: Can you use multiple @section blocks with the same name to add content? Commit to your answer.
Concept: Learn how to manage complex layouts with nested sections and content stacks.
Blade allows nested @section calls and @push/@stack directives to add content in multiple places. This helps when you want to add scripts or styles from child templates into the base layout without overwriting.
Result
You can build flexible layouts that combine content from many templates.
Understanding nested sections and stacks helps manage large projects with many reusable parts.
7
ExpertHow Blade Compiles Templates Internally
🤔Before reading on: Do you think Blade templates are interpreted at runtime or compiled beforehand? Commit to your answer.
Concept: Learn how Laravel compiles Blade templates into plain PHP for performance.
When you use Blade directives like @extends, @section, and @yield, Laravel compiles these into PHP code stored in cache. This compiled PHP runs fast and avoids parsing Blade syntax on every request.
Result
Blade templates render quickly and efficiently in production.
Knowing Blade compiles templates explains why you must clear cache after changing views sometimes.
Under the Hood
Blade templates are parsed by Laravel's view engine and converted into plain PHP files stored in a cache folder. The @extends directive tells Blade to load the parent template first. The @section directives in the child template define content blocks that replace corresponding @yield placeholders in the parent. During rendering, Laravel merges these compiled PHP files to produce the final HTML output.
Why designed this way?
Blade was designed to be simple and fast. Compiling templates ahead of time avoids runtime parsing overhead. The inheritance model keeps layouts DRY (Don't Repeat Yourself) and easy to maintain. Alternatives like raw PHP templates or complex XML-based systems were rejected for being harder to read or slower.
┌───────────────┐       ┌───────────────┐
│ Child Template│       │ Base Template │
│ @extends('base')│──────▶│ @yield('body')│
│ @section('body')│       │               │
└──────┬────────┘       └───────┬───────┘
       │                        │
       │ Compiled to PHP files  │
       └──────────────┬─────────┘
                      ▼
               ┌───────────────┐
               │ Final Rendered │
               │ HTML Output    │
               └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does @extends replace the entire base layout or just parts of it? Commit to your answer.
Common Belief:Many think @extends completely replaces the base layout with the child template.
Tap to reveal reality
Reality:@extends loads the base layout and inserts child content only into defined sections; the rest of the base layout remains intact.
Why it matters:Misunderstanding this leads to broken pages when child templates omit sections, causing missing layout parts.
Quick: Can you use @section without @yield in the base layout? Commit to your answer.
Common Belief:Some believe @section content will show even if the base layout has no @yield for it.
Tap to reveal reality
Reality:If the base layout does not have a matching @yield, the @section content is not displayed.
Why it matters:This causes confusion when content does not appear, making debugging harder.
Quick: Does Blade compile templates on every request? Commit to your answer.
Common Belief:Many assume Blade parses templates fresh on every page load.
Tap to reveal reality
Reality:Blade compiles templates once and caches the PHP version for faster rendering.
Why it matters:Not knowing this can cause confusion when changes don't appear until cache is cleared.
Quick: Can you nest @section blocks inside each other? Commit to your answer.
Common Belief:Some think nesting @section inside another @section works as expected.
Tap to reveal reality
Reality:Nesting @section blocks is not supported and causes unexpected behavior.
Why it matters:This leads to broken layouts and wasted debugging time.
Expert Zone
1
When multiple child templates extend the same base, Blade merges sections carefully to avoid overwriting unrelated content.
2
Using @parent inside a @section allows appending content to the base layout's section instead of replacing it entirely.
3
Blade's compiled PHP files include unique hashes to prevent conflicts and ensure cache validity.
When NOT to use
Template inheritance is not ideal for highly dynamic or component-based UIs where Blade components or frontend frameworks like Vue or React are better suited.
Production Patterns
In large Laravel apps, developers use a master layout with nested sections for scripts, styles, and content. They combine @extends with Blade components for reusable UI parts and use @stack/@push for injecting assets from child views.
Connections
Object-Oriented Inheritance
Template inheritance in Blade is similar to class inheritance where a child class extends a parent class and overrides methods.
Understanding class inheritance helps grasp how child templates override sections of a base layout.
Content Management Systems (CMS) Themes
CMS themes use template inheritance to allow users to customize page parts without changing the whole theme.
Knowing CMS theming shows how template inheritance enables flexible website design.
Modular Design in Architecture
Just like modular buildings reuse a base structure with customizable rooms, template inheritance reuses layout with customizable sections.
Seeing template inheritance as modular design helps appreciate its role in maintainability and scalability.
Common Pitfalls
#1Forgetting to include @yield in the base layout for a section.
Wrong approach:
Correct approach: @yield('content')
Root cause:Not understanding that @yield is required to display child section content.
#2Using @section without @extends in child templates.
Wrong approach:@section('content')

Hello

@endsection
Correct approach:@extends('base') @section('content')

Hello

@endsection
Root cause:Not realizing @section only works when extending a base layout that uses @yield.
#3Nesting @section blocks inside each other.
Wrong approach:@section('header') @section('title') Title @endsection @endsection
Correct approach:@section('header')

Title

@endsection
Root cause:Misunderstanding that Blade does not support nested sections.
Key Takeaways
Template inheritance in Laravel Blade lets you create a base layout and fill in parts with child templates using @extends, @section, and @yield.
The base layout uses @yield to mark where child content goes, and child templates use @section to provide that content.
Blade compiles templates into PHP for fast rendering, so changes may require clearing cache to appear.
Misusing or forgetting @yield or @extends causes content not to show, so understanding their roles is crucial.
Advanced features like @parent and @stack allow flexible content merging and asset management in complex layouts.