Link to Flask static files with url_for

How do you use url_for in Flask to link to 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 .

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 link to files that are not in subfolders with this, which works.

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

What is the correct way to link to static files using url_for ? How to use url_for to generate urls for static files at any level?

+48
python flask jinja2
May 03 '13 at 4:54
source share
1 answer

By default, static files use the static endpoint by default. In addition, the Flask application has the following arguments:

static_url_path : can be used to specify a different path for static files on the Internet. By default, the name of the static_folder folder is static_folder .

static_folder : folder with static files to be sent to static_url_path . By default, the static folder in the root path of the application is used.

This means that the filename argument will relate the relative path to your file in static_folder and convert it to a relative path in combination with static_url_default :

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

converts the file path from static_folder/path/to/file to the URL path static_url_default/path/to/file .

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 the default settings):

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

Also see url_for documentation .

+99
May 03 '13 at 6:36
source share



All Articles