How to load a javascript or css file into a BottlePy template?

后端 未结 3 1544
悲哀的现实
悲哀的现实 2020-12-08 03:35

I am trying to return a html template with BottlePy. And this works fine. But if I insert a javascript file like this in my tpl-file:



        
3条回答
  •  借酒劲吻你
    2020-12-08 03:56

    Well, first, you need your dev server to actually serve main.js, otherwise it won't be available for the browser.

    It's customary to put all .js and .css files under the static directory in small web apps, so your layout should look like this:

      app.py
    - static/
        main.js
    - views/
        index.tpl
    

    By no means this exact naming and layout is required, only often used.

    Next, you should supply a handler for the static files:

    from bottle import static_file
    
    # ...
    
    @route('/static/:path#.+#', name='static')
    def static(path):
        return static_file(path, root='static')
    

    This will actuall serve your files under static/ to the browser.

    Now, to the last thing. You specified your JavaScript as:

    
    

    That means the path to .js is relative to the current page. On you development server, the index page (/) will look for .js in /js/main.js, and another page (say, /post/12) will look for it in /post/12/js/main.js, and will sure fail.

    Instead, you need to use the get_url function to properly reference static files. Your handler should look like this:

    from Bottle import get_url
    
    # ...
    
    @route('/')
    @view('index')
    def index():
        return { 'get_url': get_url } 
    

    And in index.tpl, .js should be referenced as:

    
    

    get_url finds a handler with name='static', and calculates the proper path to it. For dev server, this will always be /static/. You can probably even hard-code it in the template, but I don't recommend it for two reasons:

    • You won't be able to mount your app anywhere but under root in production; i.e., when you upload it onto the porduction server, it can be placed under http://example.com/ (root), but not under http://example.com/myapp/.
    • If you change the /static/ dir location, you'll have to search it all over your templates and modify it in every single template.

提交回复
热议问题