You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中不同布局存在相同section如何遵循DRY原则优化代码

Laravel 布局重复代码优化方案

以下是三种符合DRY原则的优化方案,可根据你的Laravel版本和实际场景选择:


方案1:提取公共片段为Blade组件

Laravel 8及以上版本优先推荐该方案,可维护性更强

  • 首先在resources/views/components目录下新建hello-section.blade.php,写入重复的公共代码:
<section>
  Hello
</section>
  • 之后直接在两个布局中调用组件即可:
    布局A修改后代码:
<html>
  <body>
    <x-hello-section />
    This is 1st
    @yield('content')
  </body>
</html>

布局B修改后代码:

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

方案2:用@include引入公共片段

适合Laravel 8以下不支持Blade组件的版本:

  • 在resources/views/common目录下新建hello-section.blade.php,内容和上述组件代码完全一致
  • 在两个布局的对应位置写入@include('common.hello-section')即可调用公共片段

方案3:基础布局继承

如果两个布局整体结构相似度较高,可再进一步提取公共结构为父布局,复用率更高:

  • 新建基础父布局resources/views/layouts/base.blade.php:
<html>
  @hasSection('head')
    @yield('head')
  @endif
  <body>
    <section>
      Hello
    </section>
    @yield('prefix_text')
    @yield('content')
  </body>
</html>
  • 布局A继承基础布局:
@extends('layouts.base')

@section('prefix_text')
This is 1st
@endsection
  • 布局B继承基础布局:
@extends('layouts.base')

@section('head')
<head></head>
@endsection

@section('prefix_text')
This is 2nd
@endsection

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 09:48:03