Flask电商项目:coats.html图片正常,product.html无法加载求助
问题根源:相对路径的解析逻辑差异
这问题我刚接触Flask时也踩过坑!原因很简单:浏览器对相对路径的解析是基于当前页面的URL层级的。
你看,coats.html的页面URL是/coats,当浏览器看到<img src="static/images/coats/{{ product.image1 }}">时,会把它解析成/static/images/coats/xxx.jpg(因为Flask默认把static文件夹映射到根路径的/static路由)——刚好能命中正确的静态文件位置。
但product.html的页面URL是/product/1(假设id是1),这时浏览器会把相对路径static/images/coats/xxx.jpg解析成/product/static/images/coats/xxx.jpg,这个路径根本不存在,自然加载不出图片。
解决方案:用
url_for生成绝对路径 Flask提供了url_for函数来帮我们生成正确的静态文件路径,不管当前页面的URL是什么,它都会生成基于根目录的绝对路径。
修改你的product.html里的图片标签:
<img src="{{ url_for('static', filename='images/coats/' + product.image1) }}" class="image">
同样,为了避免以后路由层级变化再出问题,建议把coats.html里的图片路径也改成这种写法:
<a href="{{ url_for('product', id=product.id) }}"> <img src="{{ url_for('static', filename='images/coats/' + product.image1) }}" class="image"> </a>
这样不管页面路由怎么变,图片路径都是正确的/static/images/coats/xxx.jpg,就能正常加载了。
内容的提问来源于stack exchange,提问作者Glen Ottley
相关产品推荐
相关产品推荐

