Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Laravel's @yield and @include?

Tags:

laravel

I'm learning Laravel (starting at version 5.3) and those two look very much alike, the only difference I know is that @include inject parent's variables and can also send other variables.

  • What's the difference between @yield and @include?
  • When should I use @yield?
  • When should I use @include?
like image 474
Edson Horacio Junior Avatar asked Jan 28 '17 23:01

Edson Horacio Junior


People also ask

What is @yield used for in Laravel?

In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.

What is the difference between yield and section?

@yield is a section which requires to be filled in by your view which extends the layout. You could pass it a default value through the second parameter if you'd like. Usages for @yield could be the main content on your page. @section is a section which can contain a default value which you can override or append to.

What is yield (' Content ')?

Basically yield('content') is a marker. For example, in the tag if you put a yield('content') , your saying this section has the name of content and by the way, you can name inside of the parenthesis anything you want. it doesn't have to be content. it can be yield('inside'). or anything you want.

What is the use of @section in Laravel?

@section directive is inject content layout from extended blade layout and display in child blade. The content of these section will be displayed in the layout using @yield directive. @parent directive will be replaced by the content of the layout when the view is rendered.


1 Answers

@yield is mainly used to define a section in a layout. When that layout is extended with @extends, you can define what goes in that section with the @section directive in your views.

The layout usually contains your HTML, head, body, header and footers. You define an area (@yield) within the layout that your pages which are extending the template will put their content into.

In your master template you define the area. For example:

<body>      @yield('content') </body> 

Lets say your home page extends that layout

@extends('layouts.app')  @section('content')      // home page content here @endsection 

Any HTML you define in the content section on your homepage view in the 'content' section will be injected into the layout it extended in that spot.

@include is used for reusable HTML just like a standard PHP include. It does not have that parent/child relationship like @yield and @section.

I highly suggest reading the documentation on Blade Templates on the Laravel site for a more comprehensive overview

https://laravel.com/docs/5.0/templates

like image 161
Rob Fonseca Avatar answered Oct 20 '22 06:10

Rob Fonseca