Web应用程序通常需要支持网页显示的静态文件,如 javascript 文件或 CSS 文件。通常,将Web服务器配置为您提供服务,但是在开发过程中,这些文件是从软件包中或模块旁边的static文件夹提供的,可通过 /static 访问。
在下面的示例中,在 index.html 中的HTML按钮的 OnClick 事件中调用了 hello.js 中定义的 javascript 函数。在Flask应用程序的'/' URL上呈现。
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 包含 sayHello()函数。
function sayHello() { alert("Hello World") }