使用url_for链接到Flask静态文件

use*_*282 76 python jinja2 flask

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

当我尝试提供文件时static/bootstrap,我收到错误.

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

我可以引用不在子文件夹中的文件,这有效.

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

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

tbi*_*icr 158

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

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

static_folder:包含应该提供的静态文件的文件夹static_url_path.默认为应用程序根路径中的"static"文件夹.

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

url_for('static', filename='path/to/file')
Run Code Online (Sandbox Code Playgroud)

将文件路径转换为static_folder/path/to/fileurl路径static_url_default/path/to/file.

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

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

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

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Run Code Online (Sandbox Code Playgroud)

另请查看url_for文档.