Blade模板继承通过@yield和@section实现布局复用,组件化则利用<x->标签和插槽封装UI元素,结合使用提升Laravel项目前端可维护性与开发效率。

在Laravel中,Blade 是一个简单却强大的模板引擎,它允许你使用简洁的语法编写视图,并通过模板继承和组件化实现高效的页面结构复用。掌握 Blade 的继承机制与组件开发方式,能显著提升前端代码的可维护性和开发效率。
Blade 的模板继承让你可以定义一个基础页面布局,然后在不同子页面中填充特定内容。
首先创建一个通用布局文件,比如 resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>@yield('title', '默认标题')</title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<header>
<h1>我的网站</h1>
@section('sidebar')
<p>这是默认侧边栏内容</p>
@show
</header>
<main>
@yield('content')
</main>
<footer>
<p>© 2025 公司名称</p>
</footer>
</body>
</html>
说明:
接着创建子页面,例如 resources/views/home.blade.php:
@extends('layouts.app')
@section('title', '首页')
@section('sidebar')
<p>这里是首页的侧边栏</p>
@endsection
@section('content')
<h2>欢迎来到首页</h2>
<p>这是主要内容区域。</p>
@endsection
渲染时,Blade 会将子页面的内容注入到父布局对应的位置。
Blade 组件让你可以把常用的UI模块(如按钮、卡片、表单字段)封装成独立单元,在多个页面中重复使用。
以创建一个按钮组件为例:
<button type="{{ $type ?? 'button' }}" class="btn btn-{{ $variant ?? 'primary' }}">
{{ $slot }}
</button>
其中:
在视图中使用该组件:
<x-button variant="success" type="submit">
提交表单
</x-button>
<x-button variant="danger">
删除
</x-button>
Laravel 会自动解析 x- 开头的标签为 Blade 组件。
复杂组件常需要多个内容区域,这时可用命名插槽。
例如创建一个模态框组件 modal.blade.php:
<div class="modal">
<div class="modal-header">
{{ $header }}
</div>
<div class="modal-body">
{{ $slot }}
</div>
<div class="modal-footer">
{{ $footer }}
</div>
</div>
使用时通过 <x-slot> 填充指定区域:
<x-modal>
<x-slot name="header">
<h3>确认操作</h3>
</x-slot>
<p>你确定要执行此操作吗?</p>
<x-slot name="footer">
<button type="button" class="btn btn-secondary">取消</button>
<button type="button" class="btn btn-primary">确定</button>
</x-slot>
</x-modal>
此外,可通过 $attributes 接收额外HTML属性,比如class或data-*:
<button {{ $attributes->merge(['class' => 'btn']) }}>
{{ $slot }}
</button>
这样调用时可添加自定义类名:<x-button class="mx-2">点击</x-button>,最终合并输出。
基本上就这些。Blade 的模板继承适合构建整体页面结构,而组件化则利于拆分和复用UI模块。两者结合,能让 Laravel 项目的前端组织更清晰、更高效。
以上就是Laravel框架怎么使用Blade模板_Laravel模板继承与组件化开发的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号