Laravel子目录模板继承主模板后静态资源404及JS报错求助
问题
在Laravel项目中,尝试让位于/var/www/html/useradmintest_13_july_eve/useradmintest/resources/views/auth/passwords/email.blade.php的email.blade.php通过@extends('welcome')继承/var/www/html/useradmintest_13_july_eve/useradmintest/resources/views/welcome.blade.php的CSS样式,继承后控制台出现以下404错误及脚本错误:
reset:20 GET http://127.0.0.1:8000/password/css/styles.css net::ERR_ABORTED 404 (Not Found) reset:21 GET http://127.0.0.1:8000/password/css/style2.css net::ERR_ABORTED 404 (Not Found) reset:22 GET http://127.0.0.1:8000/password/css/image_slider.css net::ERR_ABORTED 404 (Not Found) reset:23 GET http://127.0.0.1:8000/password/css/validation.css net::ERR_ABORTED 404 (Not Found) reset:99 GET http://127.0.0.1:8000/password/js/scripts.js net::ERR_ABORTED 404 (Not Found) sb-forms-latest.js:5 Uncaught Error: GET_ELEMENTS: page-top -> form[data-sb-form-api-token]
解决方案
一、修复静态资源404问题
出现404是因为welcome.blade.php中使用了相对路径引用静态资源,当页面处于/password路由下时,浏览器会把资源路径解析为/password/css/xxx.css,而实际资源存放在项目根目录的public文件夹下。解决方式如下:
- 打开
welcome.blade.php,将所有静态资源的引用替换为Laravel的asset()辅助函数,确保路径为绝对路径:<!-- 原引用方式 --> <link rel="stylesheet" href="css/styles.css"> <script src="js/scripts.js"></script> <!-- 修改后 --> <link rel="stylesheet" href="{{ asset('css/styles.css') }}"> <script src="{{ asset('js/scripts.js') }}"></script> - 确认静态资源的存放位置:确保
styles.css、style2.css等文件都在public/css目录下,scripts.js在public/js目录下,这是Laravel默认的静态资源存放位置。
二、修复sb-forms脚本错误
该错误是因为sb-forms-latest.js在页面中寻找带有data-sb-form-api-token属性的表单,但email.blade.php中没有这个表单,而welcome.blade.php全局引入了该脚本。推荐两种解决方式:
- 按需加载脚本:
- 在
welcome.blade.php中把sb-forms-latest.js的引用放在自定义的@yield('scripts')区块中:<!-- 在welcome.blade.php的底部添加 --> @yield('scripts') - 在需要使用该脚本的页面(比如
welcome.blade.php本身)中,通过@push引入脚本:@push('scripts') <script src="{{ asset('js/sb-forms-latest.js') }}"></script> @endpush
email.blade.php就不会加载这个不需要的脚本,避免报错。 - 在
- 添加占位表单(仅临时应急):
在email.blade.php中添加一个隐藏的符合要求的表单:<form data-sb-form-api-token="dummy-token" style="display:none;"></form>
内容的提问来源于stack exchange,提问作者Ruby
相关产品推荐
相关产品推荐

