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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6978603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:34:01  来源:igfitidea点击:

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

javascriptpythontemplatesbottleurl-for

提问by eltorrero

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:

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

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

I get an 404 error. (Failed to load resource: the server responded with a status of 404 (Not Found))

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

Does anyone know how to fix this problem?

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

Here is my script file:

这是我的脚本文件:

from bottle import route, run, view

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

And that is the template file, located in "./views" subfolder.

这就是模板文件,位于“./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>

Maybe it is the "rootPath/js/main.js" from the development server where it looks for my js-file?

也许它是来自开发服务器的“rootPath/js/main.js”,它在那里寻找我的 js 文件?

The structure of the files is:

文件的结构是:

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

Thanks.

谢谢。

回答by Helgi

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

好吧,首先,你需要你的开发服务器来实际服务main.js,否则浏览器将无法使用它。

It's customary to put all .jsand .cssfiles under the staticdirectory in small web apps, so your layout should look like this:

通常将所有.js.css文件static放在小型网络应用程序的目录下,因此您的布局应如下所示:

  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.

这实际上会将您的文件提供static/给浏览器。

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

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

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

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

这意味着路径.js对于当前页面的。在你开发服务器,索引页(/)将寻找.js/js/main.js和另一页(说,/post/12)将寻找它/post/12/js/main.js,并且将肯定失败。

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

相反,您需要使用该get_url函数来正确引用静态文件。您的处理程序应如下所示:

from Bottle import get_url

# ...

@route('/')
@view('index')
def index():
    return { 'get_url': get_url } 

And in index.tpl, .jsshould be referenced as:

而在index.tpl,.js应引用为:

<script type="text/javascript" src="{{ get_url('static', path='main.js') }}" charset="utf-8"></script>

get_urlfinds 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:

get_url找到一个带有 的处理程序name='static',并计算到它的正确路径。对于开发服务器,这将始终是/static/. 您甚至可以在模板中对其进行硬编码,但我不建议这样做,原因有两个:

  • 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.
  • 您将无法在生产环境中的 root 下安装您的应用程序;即,当您将其上传到生产服务器时,它可以放在http://example.com/(root)下,但不能放在http://example.com/myapp/下。
  • 如果更改/static/目录位置,则必须在整个模板中搜索它并在每个模板中修改它。

回答by Paul

I think you are putting the file main.jsin the wrong location.

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

Note that this file path must be relative to the requested url, not relative to the path to your template. So putting it in a folder like template/js/main.jswill not work.

请注意,此文件路径必须相对于请求的 url,而不是相对于模板的路径。所以把它放在一个文件夹中是template/js/main.js行不通的。

回答by arsho

Here is a working approach of adding static files like CSS/JS in Bottleweb project. I am using Bootstrap and Python 3.6.

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

Project structure

项目结构

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

索引.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>

Output

输出

bottle bootstrap demo

瓶子引导程序演示