Laravel Tutorial Beginners

Laravel Blade Templates - Extending Layouts


Laravel's Blade templating engine provides a powerful way to create consistent and reusable layouts for your web application. In this guide, we'll explore how to extend layouts with Blade, allowing you to define a master layout and populate its sections with content from various views.

1. Layout Creation

Create a master layout (e.g., `layout.blade.php`) that will serve as the base for your application's views. Define the common HTML structure, including header, navigation, and footer:

        
<!DOCTYPE html>
<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>
        <nav>
            <a href=`/`>Home</a>
            <a href=`/about`>About</a>
            <a href=`/contact`>Contact</a>
        </nav>
    </header>
    <main>
        @yield('content')
    </main>
    <footer>
        <p>Copyright © 2023 Your Company</p>
    </footer>
</body>
</html>

2. Extending the Layout

In your individual views (e.g., `home.blade.php`), extend the master layout using the `@extends` directive and specify the title and content for the sections you want to populate:

        
@extends('layout')
@section('title', 'Home Page')
@section('content')
    <h1>Welcome to our website</h1>
    <p>This is the home page content.</p>
@endsection

3. Blade Sections

Use Blade sections (`@section`) to define the content that will replace the placeholders in the master layout. In the example above, `@section('title')` and `@section('content')` are defined to replace the `@yield` directives in the layout.

4. Multiple Views

Create additional views (e.g., `about.blade.php` and `contact.blade.php`) and extend the layout as shown in the previous step. Customize the title and content for each view accordingly.

5. Route Configuration

Configure your routes in the `web.php` file to display the views. For example:

        
Route::get('/', function () {
    return view('home');
});
Route::get('/about', function () {
    return view('about');
});
Route::get('/contact', function () {
    return view('contact');
});

6. Conclusion

Laravel Blade templates make it easy to create and maintain consistent layouts for your web application. By extending layouts and using sections, you can keep your HTML structure clean and DRY (Don't Repeat Yourself) while providing dynamic content for different views.

For further learning, consult the official Laravel documentation on Blade templates to explore advanced features, including conditionals, loops, and partials for building more complex views.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.