javascript - 使用 Flask 在 html 中引用 .js 文件的静态资源问题

标签 javascript python html css flask

直接打开时,我的 html 文件将加载我的 OpenLayers JavaScript 文件(加载 map 框)。但是,当我从 Flask python 应用程序运行 html 时,JavaScript 文件/对象不会加载(没有显示 map ,只有一些标题文本)。

此问题似乎已在此处排序:

External JavaScript file is not getting added when running on Flask

但是由于我的文件夹结构,我似乎无法加载 .js。没有错误,只是页面中没有加载 map 。我想我需要一些有关“静态”引用语法的帮助。我认为这就是问题所在,但是我对网站 build 非常陌生。这是我的元素文件夹结构:

ol_app.py
/pages
    olquickstart.html
/static
    /scripts
        ol_script.js
/libs
    /v6.3.1-dist
        ol.css
        ol.css.map
        ol.js
        ol.js.map

我的 Flask python 应用程序:

from flask import Flask, render_template
import os
import webbrowser
from threading import Timer

template_dir = os.path.abspath(r'D:\PathToProject\ol_quickstart\pages')
app = Flask(__name__, template_folder=template_dir)

#home page
@app.route('/')
def index():
    return '<a href="http://127.0.0.1:5000/ol_qs">OL QuickStart</a>'

#openlayers test page
@app.route('/ol_qs')
def ol_qs():
    return render_template("olquickstart.html")

#run app
def open_browser():
    webbrowser.open_new('http://127.0.0.1:5000/')

if __name__ == "__main__":
    Timer(1, open_browser).start();
    app.run(port=5000)

我的html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../libs/v6.3.1-dist/ol.css" type="text/css">
    <style>
      .map {
        height: 900px;
        width: 100%;
      }
    </style>
    <script src="../libs/v6.3.1-dist/ol.js"></script>
    <title>OpenLayers Quickstart</title>
  </head>
  <body>
    <h2>OL Quickstart Map</h2>
    <div id="js-map" class="map"></div>
    <!-- <script src='../static/scripts/ol_script.js'></script> I USE THIS LINE WHEN OPENING THE HTML DIRECTLY WITHOUT FLASK-->
    <script type="text/javascript"
        src="{{ url_for('static', filename='scripts/ol_script.js') }}"></script>
  </body>
</html>

这部分有问题吗?

<script type="text/javascript" src="{{ url_for('static', filename='scripts/ol_script.js') }}"></script>

最佳答案

看起来您需要将 libs 目录移动到 static 中,然后包含那些具有与您已有的类似 url_for 功能的文件:

<link rel="stylesheet" type="text/css"
 href="{{ url_for('static', filename='libs/v6.3.1-dist/ol.css') }}">

<script type="text/javascript"
 src="{{ url_for('static', filename='libs/v6.3.1-dist/ol.js') }}"></script>

您现有的 scripts/ol_script.js 看起来是正确的。

但是,要自行调试,您应该在网络浏览器中加载开发工具并查看 Network 选项卡,以确保每个 JS 文件成功加载并且不会出现 404。

类似地,Console 选项卡将向您显示页面中的任何 JavaScript 错误。

关于javascript - 使用 Flask 在 html 中引用 .js 文件的静态资源问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416541/

相关文章:

javascript - 当它也具有 runat ="server"时,如何使用 JavaScript 更改 html <param> 值属性

python - 删除Python RTL(从右到左)语言文本中的换行符

Python单元测试assert_used_with() false,尽管调用相同

python - 计算 2 个列表之间的匹配项(考虑顺序)

javascript - Kendo堆积柱形图分组错误

javascript - 如何使用 Javascript WebCrypto API 加载 PKCS#12 数字证书

php - 这是长轮询( cometd 编程)的正确方法吗

javascript - onclick 发送 2 个变量

javascript - 如何附加用户输入?查询

javascript - 将自定义项目添加到 extjs 中的单选按钮