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

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>
<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无法正常加载。可通过以下步骤修复:

  1. 检查文件编码与前置空白
    确保header.blade.php采用UTF-8无BOM编码,且文件第一行就是<!DOCTYPE html>,没有任何前置空格、换行或隐藏字符。编辑器默认添加的BOM或前置空白会干扰Blade解析,破坏HTML结构。

  2. 重构模板逻辑(可选)
    改用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保持原有代码即可。

  3. 清除视图缓存
    执行命令清除编译后的视图文件,确保修改生效:

    php artisan view:clear
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:45:51