Laravel布局母版页无输出求助:@yield无效页面空白
解决Laravel布局母版页空白问题的正确姿势
嘿,刚看完你的代码,你把Laravel模板继承的逻辑搞反啦!这就是页面空白的核心原因,咱们一步步把它理顺:
第一步:修正母版页 app.blade.php
母版页的作用是提供基础框架,用@yield留出给子页面填充的位置,而不是自己写@section。另外,header和footer作为固定片段,直接用@include引入就行:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <!-- 允许子页面自定义标题,默认显示Master Page --> <title>@yield('title', 'Master Page')</title> </head> <body> <!-- 引入头部片段 --> @include('header') <!-- 子页面内容的占位区 --> <div class="content"> @yield('content') </div> <!-- 引入底部片段 --> @include('footer') </body> </html>
第二步:修正header.blade.php和footer.blade.php
这两个是独立的内容片段,不需要继承母版页,去掉多余的完整HTML结构,只保留需要嵌入的内容:
header.blade.php
<style> .header { height:100px; width:100%; background-color: aquamarine; } </style> <div class="header"> <center> Layout Header Master page </center> </div>
footer.blade.php
<style> .footer { height:100px; width:100%; background-color: aquamarine; padding-top: 50px ; } </style> <div class="footer"> <center> Layout Footer Master page </center> </div>
第三步:创建子视图(比如home.blade.php)
子视图才是需要继承母版页的,用@extends绑定母版,然后用@section填充母版的占位区:
@extends('layouts.app') <!-- 注意路径:如果app在layouts文件夹下,就写layouts.app --> <!-- 自定义页面标题(可选) --> @section('title', 'My First Laravel Page') <!-- 填充母版的content占位区 --> @section('content') <h1>Body Content Here!</h1> <p>终于搞定Laravel布局啦 🎉</p> @endsection
第四步:修正控制器方法
你之前直接返回母版页,这不对,应该返回子视图,它会自动加载母版并填充内容:
public function viewmasterpage() { return view('home'); // 返回子视图home.blade.php }
为什么原来的页面是空白的?
- 你直接返回母版页
layouts/app,但母版里的@yield('header')和@yield('footer')没有对应的@section填充,母版自身的@section('content')只是定义了一个区块,没有被输出,所以页面没有实际内容。 header.blade.php和footer.blade.php错误地使用@extends('app'),这会让它们生成完整的HTML页面,而不是作为片段被母版引入,完全搞反了模板继承的逻辑。
现在访问你的路由/masterpage,就能看到完整的页面啦!
内容的提问来源于stack exchange,提问作者Parteek Kumar Kherpa
相关产品推荐
相关产品推荐

