Sunday, January 13, 2013

bottle模板引用javascript和css的问题

如果在bottle默认的sampleTemple使用javascript或者css引用时会发现引用没有效果。处理办法:


  index.py
- static/
    jquery.js
    jquery.flox.js
- views/
    hello_temple.tpl


index.py:


from bottle import Bottle, route, run, post, request, static_file, abort, view

# 需要使用 app.get_url
from bottle import default_app
app = Bottle()
default_app.push(app)

# 给所有模板目录传递路径
from bottle import SimpleTemplate
SimpleTemplate.defaults["get_url"] = app.get_url

# 定义静态脚本路径
@route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')

@route('/')
@route('/hello/<name>')
@view('hello_template')
def hello(name='World'):
    return {}



hello_template的引用方式:
<script language="javascript" type="text/javascript" src="{{ get_url('static', path='jquery.js') }}"></script>


参考:

http://stackoverflow.com/questions/10885429/static-files-in-a-bottle-application-cannot-be-found-404
http://stackoverflow.com/questions/9505256/static-files-not-loaded-in-a-bottle-application-when-the-trailing-slash-is-omitt
http://stackoverflow.com/questions/6978603/how-to-load-a-javascript-or-css-file-into-a-bottlepy-template

No comments:

Post a Comment