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

时间:2016-03-04 14:38:07

标签: laravel laravel-5 blade laravel-blade

我有以下文件:

foo.blade.php

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

bar.blade.php

<h2>Bar Template</h2>
<div class="bar-content">
@yield('bar-content')
</div>

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

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

给予:

<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>

我该怎么做?

5 个答案:

答案 0 :(得分:6)

使用多个文件。 例如;

layout.blade.php:

@include('header')

@yield('layout_content')

@include('footer')

second.blade.php

@extends('layout')

@section('layout_content')

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

@stop

third.blade.php

@extends('second.blade.php')

@section('second_content')

<h1>Hello World!</h1>

@stop

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

答案 1 :(得分:2)

我建议使用components。这是an example

在我看来layout/include有很多奇怪的逻辑,当你有很多这样的逻辑时,你就开始嵌套它们。组件非常简单。对于这些嵌套结构,组件也有插槽。

答案 2 :(得分:1)

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

//编辑:

foo文件中使用if语句尝试:

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

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

现在是儿童观点:

@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

答案 3 :(得分:1)

我认为不可能在这里做你想做的事,至少在不扩展Blade的情况下: https://laravel.com/docs/5.1/blade#extending-blade

如果我是你,我会重新构建我的观点层次结构,以保持简单。

答案 4 :(得分:-1)

acc
相关问题