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

问题描述 投票:6回答:5

我有以下文件:

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>

我怎样才能做到这一点?

laravel laravel-5 blade laravel-blade
5个回答
7
投票

使用多个文件。例如;

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,并且可以在子文件中使用


2
投票

我建议使用components。这是an example

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


1
投票

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

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


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

-1
投票
@php
$ext = '';
@endphp
@if (Request::segment(1)=='explications')
@php
$ext = '_explications'
@endphp
@endif
@extends('pages_templates/template_page_fluid'.$ext)
© www.soinside.com 2019 - 2024. All rights reserved.