Web應用程式通常需要一個靜態檔,例如支持顯示網頁的JavaScript檔或CSS檔。 通常,可以通過配置Web伺服器提供這些服務,但在開發過程中,這些檔將從包中的靜態檔夾或模組旁邊提供,它將在應用程式的/static
上提供。
使用特殊的端點“靜態”來為靜態檔生成URL。
在以下示例中,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")
}