Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link to Flask static files with url_for

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.

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') }}"> 

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?

like image 830
user1431282 Avatar asked May 03 '13 04:05

user1431282


People also ask

How do I link a static file in Flask?

To use static files in a Flask application, create a folder called static in your package or next to your module and it will be available at /static on the application. app.py is a basic example of Flask with template rendering. After running app.py we will see the webpage in http://localhost:5000/.

What does Flask's url_for () do?

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for , if there is a change in the root URL of your app then you have to change it in every page where the link is present.


1 Answers

You have by default the static endpoint for static files. Also Flask application has the following arguments:

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: 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.

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') 

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

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

Also look at url_for documentation.

like image 139
tbicr Avatar answered Oct 07 '22 20:10

tbicr