[译]Flask教程--静态文件

一个web应用常常须要javascript或css之类的静态文件来帮助网页更好的展现内容. 一般, web服务器被用来提供这种静态文件服务, 但在Flask程序的开发阶段, 这些文件须要被放置在Flask应用根目录下的static文件夹中, 启动后使用时url前缀以/static开头.javascript

在下面的例子中, hello.js文件中定义了一个javascript函数, 这个函数在index.html中能够被一个按钮的OnClick事件触发. 而这个Flask应用在被访问到'/' url时将index.html渲染.css

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/")
def index():
   return render_template("index.html")

if __name__ == '__main__':
   app.run(debug = True)

index.html以下:html

<html>
   <head>
      <script type = "text/javascript" 
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>
   <body>
      <input type = "button" onclick = "sayHello()" value = "Say Hello" />
   </body>
</html>

hello.js以下:java

function sayHello() {
   alert("Hello World")
}
相关文章
相关标签/搜索