Masonite tries to make static files extremely easy and comes with whitenoise out of the box. Whitenoise wraps the WSGI application and listens for certain URI requests that can be registered in your configuration files and serves those assets.
All configurations that are specific to static files can be found in config/filesystem.py
. In this file you'll find a constant file called STATICFILES
which is simply a dictionary of directories as keys and aliases as the value.
The directories to include as keys are simply the location of your static file locations as a relative path starting from the base of your application. For example, if your css files are in storage/assets/css
then put that folder location as the key. For the value, put the alias you want to use in your templates. For this example, we will use css/
as the alias.
For this setup, our STATICFILES
constant should look like:
Now in our templates we can use:
Which will get the storage/assets/css/style.css
file.
All templates have a static function that can be used to assist in getting locations of static files. You can specify the driver and locations you want using the driver name or dot notation.
Take this for example:
this will render:
You can also make the config location a dictionary and use dot notation:
and use the dot notation like so:
Sometimes you may need to serve files that are normally in the root of your application such as a robots.txt
or manifest.json
. These files can be aliased in your STATICFILES
directory in config/filesystem.py
. They do not have to be in the root of your project but instead could be in a storage/root
or storage/public
directory and aliased with a simple /
.
For example a basic setup would have this as your directory:
and you can alias this in your STATICFILES
constant:
You will now be able to access localhost:8000/robots.txt
and you will have your robots.txt served correctly and it can be indexed by search engines properly.
Thats it! Static files are extremely simple. You are now a master at static files!