Search code examples
pythonflasksassjinja2

Using sass with Flask and jinja2


I would like to include a sass compiler in my Flask application. Is there a generally accepted way of doing this?


Solution

  • Flask-Assets extension (which uses webassets library) can be used for that. Here's how to configure it to use pyScss compiler (implemented in Python) for SCSS:

    from flask import Flask, render_template
    from flask_assets import Environment, Bundle
    
    app = Flask(__name__)
    
    assets = Environment(app)
    assets.url = app.static_url_path
    scss = Bundle('foo.scss', 'bar.scss', filters='pyscss', output='all.css')
    assets.register('scss_all', scss)
    

    And in the template include this:

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

    SCSS files will be compiled in debug mode as well.

    pyScss only supports SCSS syntax, but there are other filters (sass, scss and compass) which use the original Ruby implementation.