Sunday, September 22, 2024
Google search engine
HomeLanguagesHow to use @yield and @section in Laravel

How to use @yield and @section in Laravel

In this tutorial guide, you will learn how to use @yield and @section directives to build modular and reusable views in laravel apps.

How to use @yield and @section in Laravel

Let’s explore the usage of @yield and @section in Laravel; is as follows:

  • Understanding @yield
    • Defining the yield
    • Injecting content
  • Utilizing @section
    • Defining sections
    • Injecting sections

Understanding @yield

The ‘@yield’ directive allows you to define a placeholder in your layout file where content from other views can be injected dynamically. Here’s how you can use it:

Defining the yield

In your layout file (e.g., layout.blade.php), use the ‘@yield’ directive to designate a specific area for content injection. For example:

<html>
    <head>
        <!-- Head content -->
    </head>
    <body>
        @yield('content')
    </body>
</html>

Injecting content

In your view file, use the ‘@section’ directive along with the corresponding yield name to provide the content that should be rendered within the placeholder. For example:

@extends('layout')
@section('content')
    <!-- Content goes here -->
@endsection

Utilizing @section

The ‘@section’ directive allows you to define named sections within your view files, which can then be injected into the layout using ‘@yield’. Here’s how you can leverage this powerful directive:

Defining sections

In your view file, use the ‘@section’ directive to define a named section along with the content that should be rendered within it. For example:

@section('sidebar')
    <!-- Sidebar content -->
@endsection

Injecting sections

In your layout file, use the ‘@yield’ directive along with the section name to specify where the content of that section should be injected. For example:

<html>
    <head>
        <!-- Head content -->
    </head>
    <body>
        @yield('content')
        @yield('sidebar')
    </body>
</html>

Conclusion

By learning the use of the ‘@yield’ and ‘@section’ directives in Laravel, you gain effective control over your application’s view, layout, and content organization. Understanding these directives enables you to create modular, reusable views that increase code maintainability and enhance development efficiency.

Recommended Tutorials

RELATED ARTICLES

Most Popular

Recent Comments