How to define and use Blade sections in Laravel templates?

Blade sections in Laravel templates allow you to define reusable sections of a template that can be easily used across multiple pages. Here's how you can define and use Blade sections:

Defining a section:

  1. Open your template file and add a @section directive followed by the name you want to give to the section, enclosed in quotes. For example: @section('content').
  2. Place the content you want to include in the section between the @section and @endsection directives.

Using a section:

  1. Open the file where you want to include the section and add a @extends directive at the top. This directive specifies the base template that includes the section. For example: @extends('layout.app').
  2. Within the file, add a @yield directive followed by the name of the section. This will output the content of the section from the base template. For example: @yield('content').

Here's an example to demonstrate how to define and use a Blade section:

Base Template (layout.app.blade.php):

<html> <head> <title>My Website</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <div class="content"> @yield('content') </div> <footer> <p>&copy; 2021 My Website</p> </footer> </body> </html>

Child Template (home.blade.php):

@extends('layout.app') @section('content') <h2>Home Page</h2> <p>This is the content of the home page.</p> @endsection

In this example, the layout.app template serves as the base template and defines a section called content. The home template extends the base template and fills in the content section with its own content.

When you render the home template, the output will be:

<html> <head> <title>My Website</title> </head> <body> <header> <h1>Welcome to My Website</h1> </header> <div class="content"> <h2>Home Page</h2> <p>This is the content of the home page.</p> </div> <footer> <p>&copy; 2021 My Website</p> </footer> </body> </html>

You can define and use as many sections as you need in your templates to create reusable components.