Laravel Blade-@ slot / @ component vs @include的优势?

问题描述 投票:33回答:3

Laravel 5.4 Blade引入了组件和插槽的概念-但我看不到它们在传统@include之上添加了什么。据我了解,使用组件/插槽,您可以:

在模板组件中-tpl.blade.php:

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

使用页面模板中的插槽,您可以这样做:

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

较旧版本提供哪些功能:

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

使用完全相同的'component-tpl.blade.php'Blade模板吗?

我想念的是什么?感谢您的见解。

克里斯

php laravel blade laravel-5.4 laravel-blade
3个回答
46
投票

如上所述,功能上没有区别,但仔细使用两者可以使刀片文件更整洁。

如果插槽中可能包含HTML,则使用组件将在刀片文件中提供更简洁的语法。

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

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

同样,如果组件没有插槽,则首选包含:

@include('test')

@component('test')
@endcomponent

13
投票

我想我已经找到了另一个关键的区别。例如,从5.4的文档中:

Blade的@include指令允许您从另一个视图中包含一个Blade视图。父视图可用的所有变量将对包含的视图可用:

据我所知,组件与包含视图具有不同的作用域,因此父视图可用的变量在组件内不可用。您需要像这样将变量传递给组件:

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

此讨论与此问题有关:Use variables inside the Markdown Mailables


5
投票

正如documentation所说:

组件和插槽与部分和布局;但是,有些人可能会发现组件的心理模型,插槽更易于理解

© www.soinside.com 2019 - 2024. All rights reserved.