flask第33篇——加載靜態文件

靜態文件主要包括cssJavaScript等腳本文件、圖片等,在加載文件的時候主要是用url_for方法。

  • 語法
url_for('文件夾', filename='調用文件路徑及擴展名')

我們先在static文件夾新建jscss文件夾,並新建對應擴展名的文件:

然後在index文件夾下新建mystatic.html文件,對應代碼:

  • mystatic.js
window.onload = function(){
    alert('hello world')
}

此代碼意思是彈出alert提示框

  • mystatic.css
body{
    background: aquamarine;
}

這裏只是設置了一下背景顏色

  • mystatic.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>靜態文件</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/mystatic.css') }}">
    <script src="{{ url_for('static', filename='js/mystatic.js') }}"></script>
</head>
<body>

</body>
</html>

注意:在mystatic.html中,分別通過linkscript標籤,利用url_for調用了對應的靜態文件。 在app.py中增加函數:

@app.route('/mystatic/')def mystatic():
    return flask.render_template('index/mystatic.html')

執行,可以在頁面看到:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章