PHP - Laravel 视图模板(blade.php) 模板继承(@extends、@yield、@section)

488 阅读1分钟

一、简介

  • 当一个页面的 头部尾部 完全一样,只要中间内容不一致,这个时候需要用到一个头尾公共的模板,然后其他页面多继承于这个公共模板编写中间内容部分即可。

  • 模板引入与使用,及模板使用页面参数

  • 模板继承格式

    // components 表示在 views 下面的 components 文件夹
    // main 表示在 views/components/main.blade.php 文件
    @extends('components.main')
    

二、简单继承使用

  • 新建一个 main.blade.php 作为公共视图文件

    <body>
      @include('components.header')
      页面内容
      @include('components.footer')
    </body>
    
  • 然后新建 header.blade.phpfooter.blade.php 文件

    <div>我是头部</div>
    
    <div>我是尾部</div>
    

    image.png

  • 然后使用 index.blade.php 继承 main.blade.php 文件

    image.png

    image.png

三、@yield 占位符,@section 输出符

  • 根据页面需求自定义公共模板中的内容,例如:页面内容,上面之前是写死内容,现在需要每个页面显示不同类容。

  • main.blade.php 文件

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      {{-- 自定义标题 --}}
      <title>@yield('title')</title>
      {{-- 自定义CSS --}}
      @yield('css')
    </head>
    <body>
      @include('components.header')
      {{-- 自定义中间内容 --}}
      @yield('content')
      @include('components.footer')
      {{-- 自定义JS --}}
      @yield('js')
    </body>
    </html>
    
  • index.blade.php 文件

    {{-- 继承 --}}
    @extends('components.main')
    
    {{-- 用法一:单标签 --}}
    @section('title', 'DzmTest')
    
    {{-- 用法二:双标签 --}}
    @section('content')
        <div class="content-view">我是页面内容</div>
    @endsection
    
    {{-- css --}}
    @section('css')
        <style>
          .content-view {
            color: red
          }
        </style>
    @endsection
    
    {{-- js --}}
    @section('js')
        <script>
          console.log('DzmTest');
        </script>
    @endsection
    
  • Demo效果

    image.png