如何在Blade(Laravel 5)中扩展多个模板?

Yah*_*din 9 laravel blade laravel-5 laravel-blade

我有以下文件:

foo.blade.php

<html>
   <head>
   </head>
   <body>
      <h1>Foo Template</h1>
      @yield('content')
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

bar.blade.php

<h2>Bar Template</h2>
<div class="bar-content">
@yield('bar-content')
</div>
Run Code Online (Sandbox Code Playgroud)

我想创建另一个能够扩展上述模板的文件.例如:

@extends('foo')
@section('content')
     <p>Hello World</p>
     @extends('bar')
     @section('bar-content')
          <p>This is in div.bar-content</p>
     @endsection
@endsection
Run Code Online (Sandbox Code Playgroud)

给:

<html>
   <head>
   </head>
   <body>
      <h1>Foo Template</h1>
      <p>Hello World</p>
      <h2>Bar Template</h2>
      <div class="bar-content">
          <p>This is in div.bar-content</p>
      </div>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Vis*_*ran 9

使用多个文件.例如;

layout.blade.php:

@include('header')

@yield('layout_content')

@include('footer')
Run Code Online (Sandbox Code Playgroud)

second.blade.php

@extends('layout')

@section('layout_content')

<div>
@yield('second_content')
</div>

@stop
Run Code Online (Sandbox Code Playgroud)

third.blade.php

@extends('second.blade.php')

@section('second_content')

<h1>Hello World!</h1>

@stop
Run Code Online (Sandbox Code Playgroud)

您可以在任何父文件中包含@yield,并且可以在子文件中使用


Art*_*sov 5

我建议使用组件。这是一个例子

在我看来,layout/include当它们很多并且你开始嵌套它们时,它似乎有一个奇怪的逻辑。组件非常简单。对于您在那里构建的这些嵌套结构,组件也有插槽。


ses*_*i98 1

我不知道这是否有效,但请尝试@include代替@extends您的bar模板。将您的部分放在bar其他部分的下面(不嵌套)。我没有测试过这个,所以我希望它能起作用;)

// 编辑:

在文件中使用 if 语句尝试一下foo

<html>
    <head>
    </head>
    <body>
    <h1>Foo Template</h1>
    @yield('content')

    @if(isset($displayBar) && $displayBar == true)
        @include('dashboard.test.bar')
    @endif
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在是子视图:

@extends('dashboard.test.foo')
@section('content')
    <p>Hello World</p>
@endsection

<?php $displayBar = true ?>

@section('bar-content')
    <p>This is in div.bar-content</p>
@endsection
Run Code Online (Sandbox Code Playgroud)