Could we help you? Please click the banners. We are young and desperately need the money
Laravel Blade is one of the most powerful templating engines in PHP, offering a clean and efficient way to manage views. Three key directives @section, @hasSection, and @yield help developers structure layouts dynamically. In this guide, we’ll explore how these directives work, their benefits, and practical use cases.
Blade is Laravel’s built-in templating engine that allows developers to create modular and reusable views. Unlike traditional PHP templates, Blade provides a simple syntax that improves readability and maintainability.
@section is used to define a section in a Blade template that can be filled with content from child views. It helps in implementing a consistent layout across multiple pages.
Syntax:
@section('title', 'Welcome to My Website')
Or with multiple lines of content:
@section('content')
    <h1>Welcome to My Laravel Website</h1>
    <p>This is a sample page using Blade templates.</p>
@endsection
@hasSection checks if a specific section has been defined in a child template before rendering content. This is useful for conditional content rendering.
Syntax:
@if (@hasSection('sidebar'))
    <div class="sidebar">
        @yield('sidebar')
    </div>
@else
    <p>No sidebar available.</p>
@endif
@yield is used to display the contents of a section that is defined within a child template. It acts as a placeholder within the base layout.
Syntax:
@yield('content')
Create a base Blade template (layouts/app.blade.php) that will be extended by other views.
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    <header>
        <h1>My Laravel App</h1>
    </header>
    <main>
        @yield('content')
    </main>
    @if (@hasSection('sidebar'))
        <aside>
            @yield('sidebar')
        </aside>
    @endif
    <footer>
        <p>© 2024 My Laravel App</p>
    </footer>
</body>
</html>
Create a child view (resources/views/home.blade.php) that extends the base layout and fills sections.
@extends('layouts.app')
@section('title', 'Home Page')
@section('content')
    <h2>Welcome to the Home Page</h2>
    <p>This page uses Blade templating with @section.</p>
@endsection
@section('sidebar')
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
    </ul>
@endsection
| Issue | Solution | 
|---|---|
| @section not rendering | Ensure you call @yield in the base template. | 
| @hasSection not working | Verify the section is defined in the child view. | 
| @yield not displaying content | Ensure the corresponding @section is defined. | 
Laravel Blade’s @section, @hasSection, and @yield directives make it easy to create structured and reusable layouts. Mastering these directives will enhance your Laravel development skills and make your templates more efficient.