Laravel Blade模板favicon无法显示 求修复方法
修复Laravel视图中Favicon显示异常问题
视图文件夹结构
/layout header.blade.php footer.blade.php template.blade.php index.blade.php
各视图文件内容
header.blade.php
<!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="{{ asset('img/favicon.png') }}"> <link rel="apple-touch-icon" href="{{ asset('img/favicon.png') }}"> <title>@yield('title')</title> </head> <body>
footer.blade.php
<script src="{{ asset('js/jquery-3.6.0.min.js') }}"></script> <script src="{{ asset('js/custom.js') }}"></script> @stack('scripts') </body> </html>
template.blade.php
@include('layout.header') @yield('content') @include('layout.footer')
index.blade.php
@extends('layout.template') @section('title', 'Title') @section('content') <div>Content</div> @endsection
渲染后异常的HTML结构
<html> <head></head> <body> <link rel="icon" href="http://localhost/project/public/img/favicon.png"> <title>testing</title> <div>Test</div> <script src="http://localhost/project/public/js/jquery-3.6.0.min.js"></script> <script src="http://localhost/project/public/js/custom.js"></script> </body> </html>
问题分析与修复方案
渲染后<head>标签为空,原本属于<head>的link、title被错误解析到<body>中,导致favicon无法正常加载。可通过以下步骤修复:
检查文件编码与前置空白
确保header.blade.php采用UTF-8无BOM编码,且文件第一行就是<!DOCTYPE html>,没有任何前置空格、换行或隐藏字符。编辑器默认添加的BOM或前置空白会干扰Blade解析,破坏HTML结构。重构模板逻辑(可选)
改用Blade原生的布局继承逻辑,减少@include嵌套可能带来的解析问题:
修改template.blade.php为母版布局:<!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="{{ asset('img/favicon.png') }}"> <link rel="apple-touch-icon" href="{{ asset('img/favicon.png') }}"> <title>@yield('title')</title> </head> <body> @yield('content') <script src="{{ asset('js/jquery-3.6.0.min.js') }}"></script> <script src="{{ asset('js/custom.js') }}"></script> @stack('scripts') </body> </html>index.blade.php保持原有代码即可。清除视图缓存
执行命令清除编译后的视图文件,确保修改生效:php artisan view:clear
内容的提问来源于stack exchange,提问作者mmdev
相关产品推荐
相关产品推荐

