使用 url_for 链接到 Flask 静态文件 [英] Link to Flask static files with url_for
问题描述
如何在 Flask 中使用 url_for
来引用文件夹中的文件?例如,我在 static
文件夹中有一些静态文件,其中一些可能在 static/bootstrap
等子文件夹中.
How do you use url_for
in Flask to reference a file in a folder? For example, I have some static files in the static
folder, some of which may be in subfolders such as static/bootstrap
.
当我尝试从 static/bootstrap
提供文件时,出现错误.
When I try to serve a file from static/bootstrap
, I get an error.
<link rel=stylesheet type=text/css href="{{ url_for('static/bootstrap', filename='bootstrap.min.css') }}">
我可以引用不在子文件夹中的文件,这很有效.
I can reference files that aren't in subfolders with this, which works.
<link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}">
使用 url_for
引用静态文件的正确方法是什么?如何使用 url_for
生成任何级别的静态文件的 url?
What is the correct way to reference static files with url_for
? How do I use url_for
to generate urls to static files at any level?
推荐答案
默认情况下,您拥有 static
端点 用于静态文件.此外,Flask
应用程序具有以下参数:
You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
:可用于为网络上的静态文件指定不同的路径.默认为 static_folder
文件夹的名称.
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
:包含应在 static_url_path
处提供的静态文件的文件夹.默认为应用程序根路径中的静态"文件夹.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
这意味着 filename
参数将采用 static_folder
中文件的相对路径,并将其转换为与 static_url_default
结合的相对路径:
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
会将文件路径从static_folder/path/to/file
转换为url路径static_url_default/path/to/file
.
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
因此,如果您想从 static/bootstrap
文件夹中获取文件,请使用以下代码:
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
将转换为(使用默认设置):
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
另请参阅url_for
文档.
Also look at url_for
documentation.
这篇关于使用 url_for 链接到 Flask 静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!