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
相关产品推荐
相关产品推荐

