Laravel Blade advantage @ slot / @ component vs @include?

Laravel 5.4 Blade introduced the concept of components and slots - but I don’t see what they add to the traditional @include. As I understand it, with components / slots you do:

In the template component-tpl.blade.php:

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

Using the slots in the page template, do the following:

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

What functionality does the older provide:

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

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

What am I missing? Thanks for any ideas.

Chris

+8
php laravel blade laravel-blade
source share
3 answers

As already mentioned, there is no functional difference, but careful use of both can give you cleaner blade files.

If the slot can contain HTML, then using the component will give cleaner syntax in your click files.

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

against

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

Equally, if the component does not have slots, then the inclusion of:

 @include('test') 

against

 @component('test') @endcomponent 
+7
source share

As the documentation reports:

Components and slots provide similar benefits for partitions and layouts; however, some may find a mental model of components and slots easier to understand .

+4
source share

I think I tracked another important difference. For example, from the documentation for 5.4:

The Blade @include directive allows you to include a Blade view from another view. All variables available for the parent view will be available for the included view:

As far as I can tell, the components have a region of differences from the containing view, so the variables available for the parent view are not available in the component. You need to pass the variable to such a component:

 @component('alert', ['foo' => 'bar']) @endcomponent 

This discussion is related to this issue: Use variables inside Markdown Mailables

+2
source share

All Articles