Laravel Blade - Advantage of @slot/@component vs @include?

ChrisNY picture ChrisNY · May 27, 2017 · Viewed 14.2k times · Source

Laravel 5.4 Blade introduced the concept of components & slots - but I can't see what they add over the traditional @include. As I understand, with component/slots, you do:

In template component-tpl.blade.php:

<div class='container'>
  <h1>{{$slot1}}</h1>
  <h2>{{$slot2}}</h2>
</div>

Using slots in page template, you do:

@component('component-tpl')
  @slot('slot1')
    The content of Slot 1
  @endslot
  @slot('slot2')
    The content of Slot 2
  @endslot
@endcomponent

What functionality does that provide over the older:

@include('component-tpl',['slot1'=>'The content of Slot 1',
'slot2'=>"The content of Slot 2"])

using the exact same 'component-tpl.blade.php' Blade template?

What am I missing? Thanks for any insights.

Chris

Answer

Rick picture Rick · Dec 22, 2017

As stated, there's no functional difference I was incorrect - see benjaminhull's answer for details on variable scoping and passing blade syntax code. The following still holds for basic usage, though.

If a slot could contain HTML, then using a component will give a cleaner syntax in your blade files.

@component('test')
   <strong>This text has html</strong>
@endcomponent

versus

@include('test', ['slot' => '<strong>This text has HTML</strong>'])

Equally, if a component has no slots, then an include may be preferred:

@include('test')

versus

@component('test')
@endcomponent