2013-05-03 47 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

相關問題