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

如何将javascript或css文件加载到BottlePy模板中?,javascript,python,templates,bottle,url-for,Javascript,Python,Templates,Bottle,Url For,我试图返回一个html模板与瓶装水。这个很好用。但是如果我在我的tpl文件中插入这样的javascript文件: <script type="text/javascript" src="js/main.js" charset="utf-8"></script> 这就是模板文件,位于“/views”子文件夹中 <!DOCTYPE html> <html lang="de"> <head> <meta cha

我试图返回一个html模板与瓶装水。这个很好用。但是如果我在我的tpl文件中插入这样的javascript文件:

<script type="text/javascript" src="js/main.js" charset="utf-8"></script>
这就是模板文件,位于“/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>

谢谢。

我想你把文件
main.js
放错位置了


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

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

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

  app.py
- static/
    main.js
- views/
    index.tpl
from Bottle import get_url

# ...

@route('/')
@view('index')
def index():
    return { 'get_url': get_url } 
绝对不需要这种精确的命名和布局,只是经常使用

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

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>
index.tpl
中,
.js
应被引用为:

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

get\u url
查找具有
name='static'
的处理程序,并计算其正确路径。对于dev服务器,这将始终是
/static/
。您甚至可以在模板中硬编码它,但我不推荐它,原因有二:

  • 你将无法在任何地方安装你的应用程序,除非在生产中的根目录下;i、 例如,当您将其上载到Production服务器时,它可以放在(root)下,但不能放在(root)下
  • 如果更改
    /static/
    目录位置,则必须在所有模板中搜索它,并在每个模板中修改它

这里是一种在瓶子web项目中添加CSS/JS等静态文件的工作方法。我正在使用引导和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)
从瓶子导入瓶子,运行\
模板、调试、静态文件
导入操作系统,系统
dirname=os.path.dirname(sys.argv[0])
app=瓶子()
调试(真)
@app.route(“/static/”)
def send_css(文件名):
返回静态文件(文件名,root=dirname+'/static/asset/css')
@app.route(“/static/”)
def send_js(文件名):
返回静态文件(文件名,root=dirname+'/static/asset/js')
@应用程序路径(“/”)
def index():
数据={“开发者姓名”:“Ahmedur Rahman Shovon”,
“开发者组织”:“Datamate Web解决方案”}
返回模板('index',data=data)
运行(应用程序,host='localhost',端口=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>

项目
切换导航
欢迎来自{{data[“developer_name”]} 这是一个模板,展示了Bootstrap中包含的可选主题样式表。使用它作为起点,通过构建或修改它来创建更独特的东西


&抄袭;2017{{数据[“开发者组织”]}

输出


您是否尝试过某种调试,比如打印出根路径和js文件夹内容?您能检查一下这个问题吗@Anuj:我已经回答了您的问题。@Helgi路由上的
.+
表达式做了什么?@Lucio,
之间的表达式是正则表达式。
字符与任何字符匹配,
+
表示除至少一个以外的任何数字。因此,正则表达式匹配任何长度至少为一个字符的字符串。感谢您提供一个简单的示例。根据运行
app.py
的方式,使用
os.path.dirname(sys.argv[0])
可能无法获得正确的路径。例如,我正在运行一个瓶子服务器作为一个守护程序服务,其中我设置了一个
WorkingDirectory
,指向
app.py
存在的位置。每当我需要任何python脚本的位置时,我都会使用这个hack
sys.path[0]
,因为python通常会在启动之前将脚本的路径加载到
sys.path
。因此,为了让您的解决方案发挥作用,我使用:
dirname=sys.path[0]+'/'
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)
<!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>