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

@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


@include and @yield are two completely different types of operations to import code into the current file.

@include - import the contents of a separate file into the current file at the location in which it is placed. i.e.:

Layout file:

< some html or other script >

@include('include.file_name') // "include." indicates the subdirectory that the file is in

< more html or other script >

Include File ( a blade file with a block of code ):

< some cool code here >

The contents of 'file_name' ( also a blade file ) is then imported in where the @include directive is located.

@yield imports code from a "section" in the child file ( the "view" blade file. ) i.e.:

Layout file:

< some html or other script >

@yield('needed_section_name')

< more html or other script >

The following section is needed in the "view" blade file that is set to "extend" that layout file.

"View" blade file:

@extends('layout.file_name')
... code as neeeded

@section('needed_section_name')
< some cool code here >
@stop

...
more code as needed

Now the layout file will import in the section of code that matches the naming used.

More on the subject here....


The difference between @yield and @include is how you use them.

If you have a static kind of content, like a navbar, this part of the page will always be in the same place in the layout. When you use @include in the layout file, the navbar will be put once per layout. But if you use @yield you will be enforced to make a @section of the navbar on every page that @extends the layout.

@yield is, on the other hand, a better choice when content is changing on all the pages but you still want to use the same layout everywhere. If you use @include you'll have to make a new layout for every page, because of the difference of content.

Tags:

Laravel