python - 配置 Flask 正确加载 Bootstrap js 和 css 文件

标签 python flask

如何使用 Flask 中的“url_for”指令正确设置,以便使用 Bootstrap 和 RGraph 的 html 页面正常工作?

假设我的 html 页面看起来像这样(部分片段):-

<!doctype html>
<html lang="en">
    <head>
            <meta charset="utf-8">
            <link href="scripts/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
            <title>HP Labs: Single Pane Of Glass (Alpha)</title>
            <script src="scripts/RGraph/libraries/RGraph.common.core.js" ></script>
            <script src="scripts/RGraph/libraries/RGraph.line.js" ></script>
            <script src="scripts/RGraph/libraries/RGraph.common.effects.js" ></script>
            <script src="scripts/RGraph/libraries/RGraph.line.js" ></script>

 ......

 </html>

这是我已经完成/想要做的:-

  1. 在我的 Flask 模块旁边创建了一个“templates”目录,并将此 html 文件放入其中。

  2. 在我的 Flask 模块旁边创建了一个“静态”目录,但我不确定要在何处使用以及使用多少“url_for”类型语句以及它们应该放在哪里。所以目前“scripts”目录是“templates”目录中的一个子目录(我知道这是不正确的)。

  3. 我希望能够正确引用所有 Bootstrap 和 RGraph js 和 css(现在看到很多 404)。

任何人都可以指导我正确配置 Flask(运行开发服务器)来执行此操作吗?现在 js 和 css 不起作用。

谢谢!

最佳答案

scripts 目录放入您的 static 子目录,然后使用:

<link href="{{ url_for('static', filename='scripts/bootstrap/dist/css/bootstrap.css') }}" rel="stylesheet">

这里的模式是:

{{ url_for('static', filename='path/inside/the/static/directory') }}

它将被静态资源的正确 URL 替换,即使您将所有这些文件切换到不同的主机(如 CDN)也是如此。

关于python - 配置 Flask 正确加载 Bootstrap js 和 css 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22047398/

相关文章:

python - Flask:[405 错误] 带有分页和 POST 请求

python-3.x - Gunicorn 没有自动启动

python - 对于要在虚拟环境和非虚拟环境中运行的 Python 3 脚本,应使用什么 shebang?

python - wxPython 语法高亮小部件

python - Flask运行错误python,虚拟环境中没有名为flask的模块

python - Django/Flask 实现 : Listen permanently to connection via HTTP or Socket.(在后台)

python - SQLAlchemy 查询,加入关系并按计数排序

python - "try: input() except KeyboardInterrupt:"有解决方法吗

python - 使用Python脚本在记事本中进行算术运算

python - 这段在 Pyqt 中创建 QPolygon 的代码正在停止我的应用程序!帮助?