Laravel blade:你能产生一个默认的局部吗?


Laravel blade: Can you yield a default partial

如果我在Laravel blade中有一个名为RightSideBar.blade.php的布局,一个区域为yield('content'),另一个为yield('sidebar')

是否有一个内置的方式来显示default partial,如果扩展RightSideBar的视图没有section('sidebar') ?

我知道你可以通过默认传递,只是想知道是否有一种方法使默认为部分。

是你可以传递一个默认值

查看文档

@yield('sidebar', 'Default Content');

当子模板没有@section('sidebar')

时,它基本上会输出一个默认输出

大多数情况下,我们需要多行默认内容,我们可以使用以下语法:

@section('section')
    Default content
@show

例如,我在模板文件中有如下内容:

@section('customlayout')
    <article class="content">
        @yield('content')
    </article>
@show

你可以看到@show和@stop/@endsection的区别:上面的代码相当于下面的代码:

@section('customlayout')
    <article class="content">
        @yield('content')
    </article>
@stop
@yield('customlayout')

在其他视图文件中,我只能设置内容:

@section('content')
    <p>Welcome</p>
@stop

或者我也可以设置一个不同的布局:

@section('content')
    <p>Welcome</p>
@stop
@section('defaultlayout')
    <div>
        @yield('content')
    </div>
@stop

@stop相当于@endsection

虽然文档只将默认值指定为字符串,但实际上您可以传递视图

@yield('sidebar', 'View::make('defaultSidebar'))

Laravel 5.2增加了一个@hasSection指令,检查是否在视图中定义了一个section。由于某些原因,5.3或5.4文档中没有提到它。

@hasSection('sidebar')
    @yield('sidebar')
@else
    @yield('default-sidebar')
@endif

测试 Laravel 8 :

@yield可以将默认内容作为第二个参数。它可以是字符串,也可以是视图文件

// user-layout.blade.php
@yield('header', View::make('layouts.header'))

你现在可以覆盖这个"头"with section

@section('header')
  <div>New Header</div>
@endsection
//// OR - you can also pass a view file as a second parameter //////
@section('header', View::make('layouts.new-header'))