How to set background image on Flask Templates?

41,976

Solution 1

This is a simple problem can solved by Flask documentation

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 :

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

Solution 2

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

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

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

Solution 3

4 years, 7 months too late, but anyways just in case someone needs help..

I found flask recognized my .jpg image was located in 'static', so adding 'static' like so "background-image: url('/static/img/home.jpg')", is adding an "extra" static. What worked for me, using the skeleton approach,

background-image: url('home.jpg');

Simple and bare, like a skeleton.

Share:
41,976

Related videos on Youtube

Yakuzhy
Author by

Yakuzhy

Updated on May 05, 2021

Comments

  • Yakuzhy
    Yakuzhy almost 3 years

    My background-image works only for this template that has @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.

  • Memphis Meng
    Memphis Meng over 3 years
    I tried this method, it seems that it only works when the directory's name is "static". Is that right?
  • Berlian
    Berlian almost 3 years
    The first method if you put your background image in html file. the second method if you put your background-image in css.

Related