Difference between yield and include laravel

Created At: 2020-10-28 18:50:04 Updated At: 2021-03-29 07:21:08

For beginners, it could be quite confusing the difference between yield and include in laravel. Let's learn yield vs include laravel, and how to use them.

Dynamic data in blade template 

@yield is used in main template or master layout. Like you want to pass meta  data from partials to laravel master blade. Then yield is very important for this implementation. To see how to use yield in laravel see the code snippet

<meta name ="description" 
content="@yield('meta_description', 
'We build e-commerce site,
 management site, Android, iOS apps,
 and teach software development courses online.
Laravel, Java, NodeJs, PHP technology.')"/>

You see we passed meta_description data to our master template from our partials.  Master layout or template can only receive this kind of dynamic SEO meta tag data using yield directive. Click the link to learn more about dynamic SEO meta tags and yield directive.

Another example is you set facebook Open Graph meta tags data using @yield. See the example below

<meta property="og:title" content="@yield('og_title','Build a website | Learn Software Development Online')"/>

Using yield directive we can dynamically set title, description, thumbnail image for Facebook post.

The same could be done for Twitter card. 

Get data from child page to master page

We can use yield to get data from child template to master template. With @yield you can define where to put the data imported from child page. In below example we put the imported data in the body section of master template.

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

of course, if you want to use yield directive in your master template, you will have to use @section directive in your partials. Master template get dynamic data from partials and show in the browser. In your partials, you will use the section directive like below

@section('content_id')
      My content for a certain page. I will include lots of content for SEO...
@endsection

section is used in your partials with @extends directive, while we can use yield in our master layout.

Include directive

@include is used for showing static content in master layout, like if you want to include header.blade.php and footer.blade.php in master template then you will use

 @include(header) 
  or 
 @include(footer) 

in your master template. So with include directive we can import certain static files in our template. You can use include both in master or child template. 

Comment

Add Reviews