如何将javascript或css文件加载到BottlePy模板中?

时间:2011-08-08 06:43:33

标签: javascript python templates bottle url-for

我正在尝试使用BottlePy返回一个html模板。这很好用。但是如果我在我的tpl文件中插入这样的javascript文件:

<script type="text/javascript" src="js/main.js" charset="utf-8"></script>

我收到404错误。 (无法加载资源:服务器响应状态为404(未找到))

有谁知道如何解决这个问题?

这是我的脚本文件:

from bottle import route, run, view

@route('/')
@view('index')
def index():
    return dict()
run(host='localhost', port=8080)

这是模板文件,位于“./views”子文件夹中。

<!DOCTYPE html>
<html lang="de">
    <head>
        <meta charset="utf-8" />
        <script type="text/javascript" src="js/main.js" charset="utf-8"></script>
    </head>
    <body>
    </body>
</html>

也许它是开发服务器中的“rootPath / js / main.js”,它在哪里查找我的js文件?

文件的结构是:

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

感谢。

3 个答案:

答案 0 :(得分:28)

首先,您需要您的开发服务器实际提供main.js,否则它将无法用于浏览器。

习惯上将所有.js.css文件放在static目录下的小型网络应用中,因此您的布局应如下所示:

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

绝不需要这种确切的命名和布局,只能经常使用。

接下来,您应该为静态文件提供处理程序:

from bottle import static_file

# ...

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

这将实际为static/下的文件提供给浏览器。

现在,到最后一件事。您将JavaScript指定为:

<script type="text/javascript" src="js/main.js" charset="utf-8"></script>

这意味着.js的路径相对到当前页面。在您的开发服务器上,索引页面(/)将在.js中查找/js/main.js,而另一个页面(例如,/post/12)将在{{1}中查找它,肯定会失败。

相反,您需要使用/post/12/js/main.js函数来正确引用静态文件。您的处理程序应如下所示:

get_url

from Bottle import get_url # ... @route('/') @view('index') def index(): return { 'get_url': get_url } 中,index.tpl应引用为:

.js

<script type="text/javascript" src="{{ get_url('static', path='main.js') }}" charset="utf-8"></script> 找到一个get_url的处理程序,并计算它的正确路径。对于开发服务器,它始终为name='static'。您甚至可以在模板中对其进行硬编码,但我不推荐它有两个原因:

  • 您将无法将应用程序安装在生产中的任何位置,但在根目录下;即,当您将其上传到产品服务器时,它可以放在http://example.com/(根)下,但不能放在http://example.com/myapp/下。
  • 如果您更改/static/目录位置,则必须在模板上搜索并在每个模板中进行修改。

答案 1 :(得分:0)

我认为您将文件main.js放在错误的位置。

请注意,此文件路径必须相对于请求的网址,而不是相对于模板的路径。因此将其放在像template/js/main.js这样的文件夹中将无效。

答案 2 :(得分:0)

这是一种在 Bottle Web项目中添加CSS / JS等静态文件的工作方法。我正在使用Bootstrap和Python 3.6。

项目结构

project
│   app.py
│   bottle.py
│
├───static
│   └───asset
│       ├───css
│       │       bootstrap-theme.css
│       │       bootstrap-theme.css.map
│       │       bootstrap-theme.min.css
│       │       bootstrap-theme.min.css.map
│       │       bootstrap.css
│       │       bootstrap.css.map
│       │       bootstrap.min.css
│       │       bootstrap.min.css.map
│       │       custom.css
│       │
│       ├───fonts
│       │       glyphicons-halflings-regular.eot
│       │       glyphicons-halflings-regular.svg
│       │       glyphicons-halflings-regular.ttf
│       │       glyphicons-halflings-regular.woff
│       │       glyphicons-halflings-regular.woff2
│       │
│       └───js
│               bootstrap.js
│               bootstrap.min.js
│               jquery.min.js
│               npm.js
│
└───views
        index.tpl

<强> app.py

from bottle import Bottle, run, \
     template, debug, static_file

import os, sys

dirname = os.path.dirname(sys.argv[0])

app = Bottle()
debug(True)

@app.route('/static/<filename:re:.*\.css>')
def send_css(filename):
    return static_file(filename, root=dirname+'/static/asset/css')

@app.route('/static/<filename:re:.*\.js>')
def send_js(filename):
    return static_file(filename, root=dirname+'/static/asset/js')

@app.route('/')
def index():
    data = {"developer_name":"Ahmedur Rahman Shovon",
            "developer_organization":"Datamate Web Solutions"}
    return template('index', data = data)

run(app, host='localhost', port = 8080)

<强>在index.tpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Bottle web project template">
    <meta name="author" content="datamate">
    <link rel="icon" href="/static/favicon.ico">        
    <title>Project</title>
    <link rel="stylesheet" type="text/css" href="/static/bootstrap.min.css">
    <script type="text/javascript" src="/static/jquery.min.js"></script>
    <script type="text/javascript" src="/static/bootstrap.min.js"></script> 
</head>
<body>
    <!-- Static navbar -->
    <nav class="navbar navbar-default navbar-static-top">
        <div class="container">
            <div class="row">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Project</a>
                </div>
                <div id="navbar" class="navbar-collapse collapse">
                    <ul class="nav navbar-nav navbar-right">
                        <li><a href="../navbar/">Home</a></li>
                        <li><a href="./">Github</a></li>
                        <li><a href="../navbar-fixed-top/">Stackoverflow</a></li>
                    </ul>
                </div><!--/.nav-collapse -->
            </div>
        </div>
    </nav>
    <div class="container">
        <div class="row">
            <div class="jumbotron">
            <h2>Welcome from {{data["developer_name"]}}</h2>
                <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>
            </div>
        </div>
        <!--./row-->
        <div class="row">
            <hr>
            <footer>
                <p>&copy; 2017 {{data["developer_organization"]}}.</p>
            </footer>           
        </div>
    </div> 
    <!-- /container -->
</body>
</html>

<强>输出

bottle bootstrap demo