Components & Slots(Laravel 5.4 的新变化系列)

file

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 资讯,我们会努力地及时更新上面的内容哦!

参考链接:https://laravel-news.com/blade-components-...

本作品采用《CC 协议》,转载必须注明作者和本文链接
Stay Hungry, Stay Foolish.
本帖由 Summer 于 5年前 加精
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2
Destiny

这个的确很不错

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!