Search code examples
pythonbottle

What is the way to reference an image from within a bottle template?


When within a bottle template file, what is the way to reference a static file? for example this one?

<body background='/static/img/digital.gif'>

Why the above relative file fails to load the image? How can i reference it correctly? If i try it as:

<body background="{{ static_file( 'digital.gif', root='./static/img' }}">

The image also fail to render.

Why Bottle fail to render the image even if no 'static_file' function is used?


Solution

  • You should add a route to your application that will return static files when they are requested. Then use the paths in html as normal paths.

    So add this:

    @app.route('/static/<filepath:path>')
    def server_static(filepath):
        return static_file(filepath, root='/path/to/static')
    

    then accessing: http://localhost:8080/static/file.txt will return '/path/to/static/file.txt'.

    Sub-folders of '/path/to/static' will also be accessible.