I'm learning Laravel (starting at version 5.3) and these two Blade directives look very similar, the only difference I know is that @include
injects the 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
?
@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 <footer>
s. 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>
Let's 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 Laravel Blade documentation for a more comprehensive description.