Components & Slots(Laravel 5.4 的新变化系列)
Laravel Blade 在 5.4 中加入 Components 和 Slots 两个新的特性。 这个功能受到 Vue.js 的启发,能够将 HTML 元素简化为可重用区域。
在 Laravel 里面一般会先写一个主布局,然后再写一个子视图去扩展它:
// layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
@yield('content')
---
// home.blade.php
@extends('layouts.app')
@section('content')
<h1>Home Page</h1>
@endsection
基于新的 Laravel Blade Components ,假设你想在主页上添加一个警报。这里有个简单的例子:
创建一个 inc/alert.blade.php
文件并添加一个特殊的 $slot
变量:
<div class="alert">
{{ $slot }}
</div>
然后写一个 home.blade.php
文件引入 inc/alert.blade.php
@extends('welcome')
@section('content')
<div>
<h1>Home Page</h1>
@component('inc.alert')
This is the alert message here.
@endcomponent
</div>
@endsection
如此便能够轻松地定义出现在 component
中 $slot
变量的文本或HTML。
使用 Slots 和 Components 重新构思视图
当然除了创建一个简单的警告,你现在还可以做其他事情。比如可以用一个带有 $slot
变量的基本布局和子视图去驱动整个设计。 下面是一个例子:
// layouts/app.blade.php
<html>
<head>
<title>{{ $title or 'Laravel News' }}</title>
</head>
<body>
<div class="container">
{{ $slot }}
</div>
</body>
</html>
然后,如果你调用 home.blade.php
,你可以这样做:
@component('layouts.app')
@slot('title')
Home Page
@endslot
<div class="col-6">
@component('inc.alert')
This is the alert message here.
@endcomponent
<h1>Welcome</h1>
</div>
<div class="col-6">
@component('inc.sidebar')
This is my sidebar text.
@endcomponent
</div>
@endcomponent
这样,@slot('title')
将解析变量 "title" ,@component
指令中的所有内容都变成一个在其被调用视图中使用的 $slot
变量。尝试简单地将 @slot
看成和 @yield
一样的东西能帮助你去更好的使用它。
Laracasts 的相关视频:Blade Components and Slots
更多的更新可以查看 Laravel 资讯,我们会努力地及时更新上面的内容哦!
本作品采用《CC 协议》,转载必须注明作者和本文链接
这个的确很不错
感谢分享