w8eight
w8eight

Reputation: 623

Multiple static folders & templates folders in flask app

Is it possible to have more than one static folder in flask app? I have some .css and .js files which I am using only for certain blueprint and would like to have the files in same directory as blueprint.

My app has structure like this:

app
|
| blueprints
| |
| | blueprint_1
| | |
| | | views.py
| | | __init__.py
| | 
| | blueprint_2
| | |
| | | views.py
| | | __init__.py
| 
| static
| |
| | css, js, etc.

And I would like to have structure like this:

app
|
| blueprints
| |
| | blueprint_1
| | |
| | | views.py
| | | __init__.py
| | | static
| | | |
| | | | certain css, js, etc
| | 
| | blueprint_2
| | |
| | | views.py
| | | __init__.py
| | | static
| | | |
| | | | certain css, js, etc
| 
| static
| |
| | css, js, etc.

And similar thing with templates. While I am using .js file in template I access it with:

{{url_for('static'), filename='jsfile'}}

Upvotes: 4

Views: 2768

Answers (1)

w8eight
w8eight

Reputation: 623

Okay, I figured it out.

According to docs, if the blueprint does not have a url_prefix, it is not possible to access the blueprint’s static folder.

The solution then is:

Add url_prefix to Blueprint:

some_blueprint = Blueprint('something', __name__, static_folder='static', url_prefix='/something')

and in the template we refer to our static folder as it follows:

{{url_for('something.static', filename=...)}}

It seems kinda weird to me, that url_prefix is necessary for it to work, but whatever.

Upvotes: 5

Related Questions