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

tanyjin 2019-06-25

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

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

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>
   <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如下:

function sayHello() {
   alert("Hello World")
}

相关推荐

yyyxxxs / 0评论 2020-05-10