小编典典

使用url_for链接到Flask静态文件

flask

如何url_for在Flask中使用引用文件夹中的文件?例如,我的static文件夹中有一些静态文件,其中一些可能位于子文件夹中static/bootstrap

当我尝试从提供文件时static/bootstrap,出现错误。

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

我可以使用此功能来引用不在子文件夹中的文件。

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

引用静态文件的正确方法是什么url_for?如何使用url_for任何级别的静态文件生成URL?


阅读 1182

收藏
2020-04-04

共1个答案

小编典典

默认情况下,你具有静态文件的static端点。还Flask应用有以下参数:

static_url_path:可用于为网络上的静态文件指定其他路径。默认为static_folder文件夹的名称。

static_folder:包含静态文件的文件夹,应在提供该文件static_url_path。默认为应用程序根路径中的“静态”文件夹。

这意味着该filename参数将采用文件的相对路径static_folder,并将其转换为以下相对路径static_url_default:

url_for('static', filename='path/to/file')

会将文件路径从static_folder/path/to/file转换为url路径static_url_default/path/to/file。

因此,如果要从static/bootstrap文件夹中获取文件,请使用以下代码:

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

将转换为(使用默认设置):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

另请参阅url_for文档。

2020-04-04