如何在 Laravel 5.6 中使用 component 和 别名
在发布的 Laravel 5.6.0 中Sebastian De Deyne 贡献了 Blade 组件别名,Laravel 5.6.4 中他添加了一个类似的功能 Blade include 别名。我们去看看,如何在你的 Laravel 5.6 项目使用这两个功能。
组件别名
你可以像使用 @component
那样将模板路径定义成一个别名,第二个参数就是别名的名字:
Blade::component('app.components.alert', 'alert');
就像下面这样通过别名来使用模板:
@alert(['type' => 'danger'])
@slot('title')
Forbidden
@endslot
You are not allowed to access this resource!
@endalert
{{-- 替换 --}}
@component('app.components.alert');
...
@endcomponent
使用组件别名的第一个显著改进是,如果你决定重定位组件文件,则您的模板不需要随处更改:
第二个我喜欢 Blade 组件别名的原因是当使用模板的时候你不需要记住文件的路径,换句话说,你需要记住你定义过的别名 (这其实不难, 只需要查看 AppServiceProvider::boot()
方法)就可以知道项目中有哪些组件别名是可用的了。
组件别名可以方便地避免了输入组件文件的完整路径,使得组件看起来更具表达性。
Include别名
Blade include 别名从 Laravel 5.6.5 可用。 这与组件别名一样,但是相较于 @include
, 它适用于没有设置插槽的HTML:
@input(['type' => 'email'])
鉴于上面的模板使用情况,这儿 include 看起来是这样的:
<input type="{{ $type ?? 'text' }}">
下面注册 include 别名:
Blade::include('includes.input');
如果你觉得定义的别名冗长,你还可以传入第二个参数来自定义别名名称:
{{-- 默认的名称 --}}
Blade::include('includes.input', 'input');
{{-- 自定义的名称 --}}
Blade::include('includes.input', 'textinput');
若想要了解更多关于 Blade 组件别名请访问文档 Components and Slots。
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: