Skip to content

ChristinaVoss/flask-with-sass

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Flask with Sass

It can be a bit tricky to find info on how to use Sass with Flask, as most tutorials just use Bootstrap. This repo contains only the parts needed to use Sass, to make it clear what parts are involved, with a slightly organised filestructure.

Here we create a "project" folder in the overall flask-assets folder, which will hold most of our code. We use app.py at the top level just as an entry point to run the app. All configurations for the app are set up in a __init__.py file inside the project folder. (When looking at the parts used in the file structure, ignore LICENCE, README.md, .gitignore files and the .git folder, which are all related to using git. Also ignore any files with the word "cache" in it, as they are autogenerated by Flask and Python.)

Screenshot 2022-05-12 at 09 35 32

Parts needed

In __init__.py, import Environment and Bundle from flask_assets:

from flask_assets import Environment, Bundle

Then create the app and set up, register and build the assets in the same file:

app = Flask(__name__)
assets = Environment(app)

# create bundle for Flask-Assets to compile and prefix scss to css
css = Bundle('src/scss/main.scss',
             filters=['libsass'],
             output='dist/css/styles.css',
             depends='src/scss/*.scss')

assets.register("asset_css", css)
css.build()

In the head of the HTML, use the assets to link to the css file:

{% assets "asset_css" %}
  <link rel="stylesheet" type="text/css" href="{{ ASSET_URL }}"/>
{% endassets %}

Finally, create a static folder in the project one to hold the assets, including a dist folder (for output css), a src folder (to hold all the scss files) and any other folders, such as for images etc. Make sure the "depends" path given in Bundle() matches the actual path for your scss files (no need to includ "static" in the path - Flask Assets expect the project to have it).

Setup

First create and activate some form of environment to store your dependencies. I like Anaconda:

$ conda create -n myenv python=3.7

$ conda activate myenv

Then install Flask, Flask-Assets and libsass

$ pip install Flask Flask-Assets libsass

Run the app

$ export FLASK_APP=app.py
$ flask run

You should now be able to see the output in your browser window (at http://127.0.0.1:5000)

Screenshot of app running in browser

Screenshot 2022-05-12 at 18 02 25