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‘刀片模板?
我遗漏了什么?感谢你的见解。
克里斯
发布于 2018-01-25 16:12:29
我想我已经找到了另一个关键的区别。例如,从5.4的文档中:
include刀片的@
指令允许您从另一个视图中包含刀片视图。父视图可用的所有变量都将可用于包含的视图:
据我所知,组件的作用域与包含视图的作用域不同,因此可用于父视图的变量在组件中不可用。您需要将变量传递给组件,如下所示:
@component('alert', ['foo' => 'bar'])
@endcomponent发布于 2020-06-24 05:35:42
这里有两个关键的区别。
1.变量作用域
正如@DavidHyogo的答案中所描述的,一个组件只看到显式传递给它的变量。所以你必须给它所有的变量,就像这样...
@component('my-component', ['foo' => 'bar', 'etc' => 'etc'])而include默认情况下会采用全局/当前作用域中的所有变量-除非你定义了一组显式的变量来传递它,然后它又变成了局部作用域。
{{-- This include will see all variables from the global/current scope --}}
@include('my-component')
{{-- This include will only see the variables explicitly passed in --}}
@include('my-component', ['foo' => 'bar', 'etc' => 'etc']) 2.组件的{{ $slot }}与包含的{{ $var }}
当在组件中使用{{ $slot }}时,您可以给它提供刀片语法代码,例如...
{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>@component('alert')
<div>Hello {{ $name }} @include('welcome-message')</div>
@endcomponent注意插槽将如何接收html和刀片语法代码并处理它。
对于includes,这是不可能的,因为您只能将变量传递到includes...
{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>@include('alert', ['slot' => "I CAN'T PASS IN BLADE SYNTAX HERE!"])这可以通过获取一个新的view()帮助器并传递给它一些变量来编译我们想要传递到插槽中的输出,但这就是组件的用途。
发布于 2017-05-27 10:29:48
正如documentation所说:
组件和插槽为部分和布局提供了类似的好处;但是,一些人可能会发现组件和插槽的心理模型更容易理解。
https://stackoverflow.com/questions/44212318
复制相似问题