Package: django-sass-processor
django-sass-processorAnnoyed having to run a Compass, Grunt or Gulp daemon while developing Django projects?Well, then this app is for you! Compile SASS/SCSS files on the fly without having to manage
third party services nor special IDE plugins.Other good reasons for using this libraryRefer SASS/SCSS files directly from your sources, instead of referring a compiled CSS file,
having to rely on another utility which creates them from SASS/SCSS files, hidden in
your source tree.Use Django'ssettings.pyfor the configuration of paths, box sizes etc., instead of having another
SCSS specific file (typically_variables.scss), to hold these.Extend your SASS functions by calling Python functions directly out of your Django project.View SCSS errors directly in the debug console of your Django's development server.django-sass-processorconverts*.scssor*.sassfiles into*.csswhile rendering
templates. For performance reasons this is done only once, since the preprocessor keeps track on
the timestamps and only recompiles, if any of the imported SASS/SCSS files is younger than the
corresponding generated CSS file.IntroductionThis Django app provides a templatetag{% sass_src 'path/to/file.scss' %}, which can be used
instead of the built-in templatetagstatic. This templatetag also works inside Jinja2 templates.If SASS/SCSS files shall be referenced through theMediaclass, ormediaproperty, the SASS
processor can be used directly.Additionally,django-sass-processoris shipped with a management command, which can convert
the content of all occurrences inside the templatetagsass_srcas an offline operation. Hence
thelibsasscompiler is not required in a production environment.During development, asourcemapis
generated along side with the compiled*.cssfile. This allows to debug style sheet errors much
easier.With this tool, you can safely remove your Ruby installations "Compass" and "SASS" from your Django
projects. You neither need any directory "watching" daemons based on node.js.Project's HomeOn GitHub:https://github.com/jrief/django-sass-processorPlease use the issue tracker to report bugs or propose new features.Installationpip install libsass django-compressor django-sass-processordjango-compressoris required only for offline compilation, when using the commandmanage.py compilescss.libsassis not required on the production environment, if SASS/SCSS files have been precompiled
and deployed using offline compilation.ConfigurationInsettings.pyadd to:INSTALLED_APPS=[...'sass_processor',...]django-sass-processoris shipped with a special finder, to locate the generated*.cssfiles
in the directory referred bySTORAGES['sass_processor']['ROOT'](for Django >= 4.2.) orSASS_PROCESSOR_ROOT(for Django <= 4.1.), or, if unsetSTATIC_ROOT. Just add it to
yoursettings.py. If there is noSTATICFILES_FINDERSin yoursettings.pydon't forget
to include theDjangodefault finders.STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder','sass_processor.finders.CssFinder',...]Optionally, add a list of additional search paths, the SASS compiler may examine when using the@import "...";statement in SASS/SCSS files:importosSASS_PROCESSOR_INCLUDE_DIRS=[os.path.join(PROJECT_PATH,'extra-styles/scss'),os.path.join(PROJECT_PATH,'node_modules'),]Additionally,django-sass-processorwill traverse all installed Django apps (INSTALLED_APPS)
and look into their static folders. If any of them contain a file matching the regular expression
pattern^_.+\.(scss|sass)$(read: filename starts with an underscore and is of typescssorsass), then that app specific static folder is added to thelibsassinclude dirs. This
feature can be disabled in your settings with:SASS_PROCESSOR_AUTO_INCLUDE=FalseIf inside of your SASS/SCSS files, you also want to import (using@import "path/to/scssfile";)
files which do not start with an underscore, then you can configure another Regex pattern in your
settings, for instance:SASS_PROCESSOR_INCLUDE_FILE_PATTERN=r'^.+\.scss$'will look for all files of typescss. Remember that SASS/SCSS files which start with an
underscore, are intended to be imported by other SASS/SCSS files, while files starting with a
letter or number are intended to be included by the HTML tag<link href="{% sass_src 'path/to/file.scss' %}" ...>.During development, or whenSASS_PROCESSOR_ENABLED = True, the compiled file is placed into the
folder referenced bySTORAGES['sass_processor']['ROOT'](for Django >= 4.2.) orSASS_PROCESSOR_ROOT(for Django <= 4.1.).
If unset, this setting defaults toSTATIC_ROOT.
Having a location outside of the working directory prevents to pollute your localstatic/css/...directories with auto-generated files. Therefore assure, that this directory is writable by the
Django runserver.Fine tune SASS compiler parameters insettings.py.IntegerSASS_PRECISIONsets floating point precision for output css. libsass'
default is5. Note:bootstrap-sassrequires8, otherwise various
layout problemswilloccur.SASS_PRECISION=8SASS_OUTPUT_STYLEsets coding style of the compiled result, one ofcompact,compressed,expanded, ornested. Default isnestedforDEBUGandcompressedin production.Note:libsass-python0.8.3 hasproblem encoding result while saving on
Windows, the issue is already
fixed and will be included in futurepippackage release, in the meanwhile
avoidcompressedoutput style.SASS_OUTPUT_STYLE='compact'Jinja2 supportsass_processor.jinja2.ext.SassSrcis a Jinja2 extension. Add it to your Jinja2 environment to enable the tagsass_src, there is no need for aloadtag. Example of how to add your Jinja2 environment to Django:Insettings.py:TEMPLATES=[{'BACKEND':'django.template.backends.jinja2.Jinja2','DIRS':[],'APP_DIRS':True,'OPTIONS':{'environment':'yourapp.jinja2.environment'},...}]Make sure to add the default template backend, if you're still using Django templates elsewhere.
This is covered in theUpgrading templates documentation.Inyourapp/jinja2.py:# Include this for Python 2.from__future__importabsolute_importfromjinja2importEnvironmentdefenvironment(**kwargs):extensions=[]if'extensions'notinkwargselsekwargs['extensions']extensions.append('sass_processor.jinja2.ext.SassSrc')kwargs['extensions']=extensionsreturnEnvironment(**kwargs)If you want to make use of thecompilescsscommand, then you will also have to add the following to your settings:fromyourapp.jinja2importenvironmentCOMPRESS_JINJA2_GET_ENVIRONMENT=environmentUsageIn your Django templates{%loadsass_tags%}<link href="{%sass_src'myapp/css/mystyle.scss'%}" rel="stylesheet" type="text/css" />The above template code will be rendered as HTML<linkhref="/static/myapp/css/mystyle.css"rel="stylesheet"type="text/css"/>You can safely use this templatetag inside aSekizai's{% addtoblock "css" %}statement.In Media classes or propertiesIn Python code, you can access the API of the SASS processor directly. This for instance is useful
in Django's admin or form framework.fromsass_processor.processorimportsass_processorclassSomeAdminOrFormClass(...):...classMedia:css={'all':[sass_processor('myapp/css/mystyle.scss')],}Add vendor prefixes to CSS rules using values fromhttps://caniuse.com/Writing SCSS shall be fast and easy and you should not have to care, whether to add vendor specific
prefixes to your CSS directives. Unfortunately there is no pure Python package to solve this, but
with a few node modules, we can add this to our process chain.As superuser installnpminstall-gnpxand inside your project root, installnpminstallpostcss-cliautoprefixerCheck that the path ofnode_modulescorresponds to its entry in the settings directiveSTATICFILES_DIRS(see below).In casenpxcan not be found in your system path, use the settings directiveNODE_NPX_PATH = /path/to/npxto point to that executable.If everything is setup correctly,django-sass-processoradds all required vendor prefixes to
the compiled CSS files. For further information, refer to theAutoprefixerpackage.To disable autoprefixing, setNODE_NPX_PATH = None.Important note: Ifnpxis installed, butpostcssand/orautoprefixerare missing
in the localnode_modules, settingNODE_NPX_PATHtoNoneis manadatory, otherwisedjango-sass-processordoes not know how to postprocess the generated CSS files.Offline compilationIf you want to precompile all occurrences of your SASS/SCSS files for the whole project, on the
command line invoke:./manage.pycompilescssThis is useful for preparing production environments, where SASS/SCSS files can't be compiled on
the fly.To simplify the deployment, the compiled*.cssfiles are stored side-by-side with their
corresponding SASS/SCSS files. After compiling the files run./manage.pycollectstaticas you would in a normal deployment.In case you don't want to expose the SASS/SCSS files in a production environment,
deploy with:./manage.pycollectstatic--ignore=*.scssTo get rid of the compiled*.cssfiles in your local static directories, simply reverse the
above command:./manage.pycompilescss--delete-filesThis will remove all occurrences of previously generated*.cssfiles.Or you may compile results to theSTORAGES['sass_processor']['ROOT'][Django >= 4.2.] orSASS_PROCESSOR_ROOT[Django <= 4.1.] directory directy (if not specified - toSTATIC_ROOT):./manage.pycompilescss--use-storageCombine with--delete-filesswitch to purge results from there.If you use an alternative templating engine set its name in--engineargument. Currentlydjangoandjinja2are supported, seedjango-compressor documentationon how to
set upCOMPRESS_JINJA2_GET_ENVIRONMENTto configure jinja2 engine support.During offline compilationdjango-sass-processorparses all Python files and looks for
invocations ofsass_processor('path/to/sassfile.scss'). Therefore the string specifying
the filename must be hard coded and shall not be concatenated or being somehow generated.Alternative templatesBy default,django-sass-processorwill locate SASS/SCSS files from .html templates,
but you can extend or override this behavior in your settings with:SASS_TEMPLATE_EXTS=['.html','.jade']Configure SASS variables through settings.pyIn SASS, a nasty problem is to set the correct include paths for icons and fonts. Normally this is
done through a_variables.scssfile, but this inhibits a configuration through your projectssettings.py.To avoid the need for duplicate configuration settings,django-sass-processoroffers a SASS
function to fetch any arbitrary configuration directive from the project'ssettings.py. This
is specially handy to set the include path of your Glyphicons font directory. Assume, Bootstrap-SASS
has been installed using:npminstallbootstrap-sassthen locate the directory namednode_modulesand add it to your settings, so that your fonts are
accessible through the Django'sdjango.contrib.staticfiles.finders.FileSystemFinder:STATICFILES_DIRS=[...('node_modules','/path/to/your/project/node_modules/'),...]NODE_MODULES_URL=STATIC_URL+'node_modules/'With the SASS functionget-setting, it is possible to override any SASS variable with a value
configured in the project'ssettings.py. For the Glyphicons font search path, add this to your_variables.scss:$icon-font-path:unquote(get-setting(NODE_MODULES_URL)+"bootstrap-sass/assets/fonts/bootstrap/");and@import "variables";whenever you need Glyphicons. You then can safely remove any font
references, such as<link href="/path/to/your/fonts/bootstrap/glyphicons-whatever.ttf" ...>from you HTML templates.Configure SASS variables through Python functionsIt is even possible to call Python functions from inside any module. Do this by addingSASS_PROCESSOR_CUSTOM_FUNCTIONSto the project'ssettings.py. This shall contain a mapping
of SASS function names pointing to a Python function name.Example:SASS_PROCESSOR_CUSTOM_FUNCTIONS={'get-color':'myproject.utils.get_color',}This allows to invoke Python functions out of any*.scssfile.$color:get-color(250,10,120);Here we pass the parameters '250, 10, 120' into the functiondef get_color(red, green, blue)in Python modulemyproject.utils. Note that this function receives the values assass.Number,
hence extract values usingred.value, etc.If one of these customoized functions returns a value, which is not a string, then convert it
either to a Python string or to a value of typesass.SassNumber. For other types, refer to their
documentation.Such customized functions must accept parameters explicilty, otherwisesass_processordoes not
know how to map them. Variable argument lists therefore can not be used.Error reportingWheneverdjango-sass-processorruns in debug mode and fails to compile a SASS/SCSS file, it
raises asass.CompileErrorexception. This shows the location of the error directly on the
Django debug console and is very useful during development.This behaviour can be overridden using the settings variableSASS_PROCESSOR_FAIL_SILENTLY.
If it is set toTrue, instead of raising that exception, the compilation error message is send
to the Django logger.Using other storage backends for compiled CSS filesUnder the hood, SASS processor will use any storage configured in your settings asSTORAGES['staticfiles'].
This means you can use anything you normally use for serving static files, e.g. S3.A custom Storage class can be used if your deployment needs to serve generated CSS files from elsewhere,
e.g. when your static files storage is not writable at runtime and you nede to re-compile CSS
in production. To use a custom storage, configure it inSTORAGES['sass_processor']['BACKEND']. You can also
configure a dictionary with options that will be passed to the storage class as keyword arguments
inSTORAGES['sass_processor']['OPTIONS'][Django >= 4.2.] orSASS_PROCESSOR_STORAGE_OPTIONS[Django <= 4.1.>]
(e.g. if you want to useFileSystemStorage, but with a differentlocationorbase_url:# For Django >= 4.2.*STORAGES['sass_processor']={'BACKEND':'django.core.files.storage.FileSystemStorage','OPTIONS':{'location':'/srv/media/generated','base_url':'https://media.myapp.example.com/generated'}}# For Django <= 4.1.*SASS_PROCESSOR_STORAGE='django.core.files.storage.FileSystemStorage'SASS_PROCESSOR_STORAGE_OPTIONS={'location':'/srv/media/generated','base_url':'https://media.myapp.example.com/generated'}Amazon's S3 StorageUsing the S3 storage backend fromdjango-storageswith its regular configuration (if you do not otherwise use it for service static files):# For Django >= 4.2.*STORAGES['sass_processor']={'BACKEND':'storages.backends.s3boto3.S3Boto3Storage'}# For Django <= 4.1.*SASS_PROCESSOR_STORAGE='storages.backends.s3boto3.S3Boto3Storage'HerokuIf you are deploying toHeroku, use theheroku-buildpack-django-sassbuildpack to automatically compile scss for you.DevelopmentTo run the tests locally, clone the repository, and, in your local copy, create a new virtualenv.
these commands:python-mpipinstall--upgradepip
pipinstallDjango
pipinstall-rtests/requirements.txt
python-mpytesttestsThird Party DocumentationBrian wrote a nice artice onhow to easily use SASS/SCSS with Django.