📜  laravel @extends - PHP (1)

📅  最后修改于: 2023-12-03 14:43:44.479000             🧑  作者: Mango

Laravel @extends - PHP

As a Laravel developer, you might have come across the concept of @extends in Blade templates. This directive extends a layout and allows you to easily reuse the same layout across multiple pages while still having the flexibility to override specific sections of the layout.

How it works

The @extends directive is followed by the name of the layout file you want to extend. For example:

@extends('layouts.app')

This tells Blade to inherit all the markup and logic defined in the layouts/app.blade.php file.

From there, you can use the @section directive to define sections that can be overridden in child templates or views. For example:

@section('content')
    <div class="container">
        <h1>Welcome to my website</h1>
        <p>Here you'll find all sorts of interesting content</p>
    </div>
@endsection

This creates a content section that can be replaced or appended to in a child view.

Inheritance hierarchy

When you create a child view that extends a layout file, Laravel knows to look for the corresponding sections in that file and replaces them with the content from the child view.

For example, if you create a file called home.blade.php and extend the app layout, Laravel will look for a content section in app.blade.php and replace it with the contents of the home view.

If the home view also defines a sidebar section, it can be appended to the sidebar section in the app layout by using the @parent directive:

@section('sidebar')
    @parent

    <div class="sidebar-container">
        <h2>Latest Posts</h2>
        <ul>
            <li><a href="#">Post 1</a></li>
            <li><a href="#">Post 2</a></li>
            <li><a href="#">Post 3</a></li>
        </ul>
    </div>
@endsection

This adds the latest posts section to the existing sidebar contents in app.blade.php.

Conclusion

The @extends and @section directives are powerful tools for organizing your views and providing consistent layouts across your application. With Laravel, you can easily reuse your layouts and make changes in one place without having to update every single view that uses it.