2013-05-03 26 views
51

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

当我尝试从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?

回答

105

对于静态文件,您的默认设置为static endpoint。另外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') 

将文件路径转换从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 documentation

相关问题