Python 如何在 Flask 模板上设置背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39579666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:29:27  来源:igfitidea点击:

How to set background image on Flask Templates?

pythonhtmlcssflask

提问by Yakuzhy

My background-image works only for this template that has @app.route('/').

我的背景图像仅适用于具有@app.route('/') 的模板。

 <header class="intro-header" style="background-image: url('static/img/home.jpg')">

This works perfectly fine when:

这在以下情况下非常有效:

@app.route('/')
def home():
    return render_template('post.html')

Everything works. I get this:

一切正常。我明白了:

127.0.0.1 - - [19/Sep/2016 21:07:11] "GET /static/img/home.jpg HTTP/1.1" 304 

But when I use same template with:

但是当我使用相同的模板时:

@app.route('/post/')
def post():
     return render_template('post.html')

I get this:

我明白了:

127.0.0.1 - - [19/Sep/2016 21:15:23] "GET /post/static/img/home.jpg HTTP/1.1" 404 -                                                                          

And background-image is blank.

和背景图像是空白的。

回答by Hamed Mahmoudkhani

This is a simple problem can solved by Flask documentation

这是一个可以通过 Flask 文档解决的简单问题

Anyway, you should use something like this in your template:

无论如何,你应该在你的模板中使用这样的东西:

background-image: url({{ url_for('static', filename='img/home.jpg') }})

but if you don't want to use Flask methods use :

但如果您不想使用 Flask 方法,请使用:

url('/static/img/home.jpg')

or use another web server instead of flask default web server for your files like Apache and access via http://yoursite/static/img/home.jpg

或者使用另一个 Web 服务器而不是 Flask 默认 Web 服务器来为您的文件(如 Apache 和通过访问) http://yoursite/static/img/home.jpg

回答by Andy

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document - w3 CSS

部分 URL 相对于样式表的源进行解释,而不是相对于文档 - w3 CSS

This means that you need to change your url()a bit, to include the leading /.

这意味着您需要url()稍微更改一下,以包含领先的/.

"background-image: url('/static/img/home.jpg')"