【问题标题】:Laravel - Same section used in different layoutLaravel - 相同的部分用于不同的布局
【发布时间】:2021-11-20 13:18:10
【问题描述】:

我有 2 个布局,如下所示:

布局A

<html>
  <body>
    <section>
      Hello
    </section>
    This is 1st
    @yield('content')
  </body>
</html>

布局B

<html>
  <head></head>
  <body>
    <section>
      Hello
    </section>
    This is 2nd
    @yield('content')
  </body>
</html>

布局 A 和 B 都具有相同的部分。 我可以做些什么来保持代码干燥?

【问题讨论】:

    标签: laravel laravel-blade


    【解决方案1】:

    选项 1

    在 resources/views/ 创建一个 layouts/ 目录,并在其中创建一个名为“main.blade.php”的文件。

    <html>
      <body>
        <section>
        Hello
        </section>
        @yield('title')
        @yield('content')
      </body>
    </html>
    

    然后在上面的两个视图中,您将使用:

    @extends('layouts/main')
    @section('title')
        This is 1st / This is 2nd (as the case may be)
    @stop
    @section('content')
        Content goes here
    @stop
    

    选项 2

    使用包含 - 在 resources/views/ 中创建一个 includes/ 目录,并在该目录中创建 section.blade.php 的内容:

    <section>
      Hello
    </section>
    

    那么在你上面的两个视图中:

    <html>
      <body>
        @include('includes.section')
        This is 1st / This is 2nd (as the case may be)
      </body>
    </html>
    

    【讨论】:

    • 选项 2 最适合我的情况。非常感谢!
    • 没问题。当您更深入地了解事物时,请查看 Blade 中的组件 (laravel.com/docs/8.x/blade#components),因为它与上述原理相同,但提供了更大的灵活性。
    猜你喜欢
    • 2016-10-13
    • 2019-12-31
    • 2016-12-07
    • 2011-04-15
    • 1970-01-01
    • 2021-08-29
    • 2017-04-11
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多