# django-sass-processor
Annoyed 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.
[![Build Status](https://github.com/jrief/django-sass-processor/actions/workflows/tests.yml/badge.svg)](https://github.com/jrief/django-sass-processor/actions)
[![PyPI](https://img.shields.io/pypi/pyversions/django-sass-processor.svg)]()
[![PyPI version](https://img.shields.io/pypi/v/django-sass-processor.svg)](https://pypi.python.org/pypi/django-sass-processor)
[![PyPI](https://img.shields.io/pypi/l/django-sass-processor.svg)]()
[![Downloads](https://img.shields.io/pypi/dm/django-sass-processor.svg)](https://pypi.python.org/pypi/django-sass-processor)
[![Twitter Follow](https://img.shields.io/twitter/follow/shields_io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/jacobrief)
## Other good reasons for using this library
* Refer 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's `settings.py` for 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-processor** converts `*.scss` or `*.sass` files into `*.css` while 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.
## Introduction
This Django app provides a templatetag `{% sass_src 'path/to/file.scss' %}`, which can be used
instead of the built-in templatetag `static`. This templatetag also works inside Jinja2 templates.
If SASS/SCSS files shall be referenced through the `Media` class, or `media` property, the SASS
processor can be used directly.
Additionally, **django-sass-processor** is shipped with a management command, which can convert
the content of all occurrences inside the templatetag `sass_src` as an offline operation. Hence
the **libsass** compiler is not required in a production environment.
During development, a [sourcemap](https://developer.chrome.com/devtools/docs/css-preprocessors) is
generated along side with the compiled `*.css` file. 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 Home
On GitHub:
https://github.com/jrief/django-sass-processor
Please use the issue tracker to report bugs or propose new features.
## Installation
```
pip install libsass django-compressor django-sass-processor
```
`django-compressor` is required only for offline compilation, when using the command
`manage.py compilescss`.
`libsass` is not required on the production environment, if SASS/SCSS files have been precompiled
and deployed using offline compilation.
## Configuration
In `settings.py` add to:
```python
INSTALLED_APPS = [
...
'sass_processor',
...
]
```
**django-sass-processor** is shipped with a special finder, to locate the generated `*.css` files
in the directory referred by `STORAGES['sass_processor']['ROOT']` (for Django >= 4.2.*) or
`SASS_PROCESSOR_ROOT` (for Django <= 4.1.*), or, if unset `STATIC_ROOT`. Just add it to
your `settings.py`. If there is no `STATICFILES_FINDERS` in your `settings.py` don't forget
to include the **Django** [default finders](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-STATICFILES_FINDERS).
```python
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:
```python
import os
SASS_PROCESSOR_INCLUDE_DIRS = [
os.path.join(PROJECT_PATH, 'extra-styles/scss'),
os.path.join(PROJECT_PATH, 'node_modules'),
]
```
Additionally, **django-sass-processor** will 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 type `scss` or
`sass`), then that app specific static folder is added to the **libsass** include dirs. This
feature can be disabled in your settings with:
```python
SASS_PROCESSOR_AUTO_INCLUDE = False
```
If 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:
```python
SASS_PROCESSOR_INCLUDE_FILE_PATTERN = r'^.+\.scss$'
```
will look for all files of type `scss`. 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 when `SASS_PROCESSOR_ENABLED = True`, the compiled file is placed into the
folder referenced by `STORAGES['sass_processor']['ROOT']` (for Django >= 4.2.*) or `SASS_PROCESSOR_ROOT` (for Django <= 4.1.*).
If unset, this setting defaults to `STATIC_ROOT`.
Having a location outside of the working directory prevents to pollute your local `static/css/...`
directories with auto-generated files. Therefore assure, that this directory is writable by the
Django runserver.
#### Fine tune SASS compiler parameters in `settings.py`.
Integer `SASS_PRECISION` sets floating point precision for output css. libsass'
default is `5`. Note: **bootstrap-sass** requires `8`, otherwise various
layout problems _will_ occur.
```python
SASS_PRECISION = 8
```
`SASS_OUTPUT_STYLE` sets coding style of the compiled result, one of `compact`,
`compressed`, `expanded`, or `nested`. Default is `nested` for `DEBUG`
and `compressed` in production.
Note: **libsass-python** 0.8.3 has [problem encoding result while saving on
Windows](https://github.com/dahlia/libsass-python/pull/82), the issue is already
fixed and will be included in future `pip` package release, in the meanwhile
avoid `compressed` output style.
```python
SASS_OUTPUT_STYLE = 'compact'
```
### Jinja2 support
`sass_processor.jinja2.ext.SassSrc` is a Jinja2 extension. Add it to your Jinja2 environment to enable the tag `sass_src`, there is no need for a `load` tag. Example of how to add your Jinja2 environment to Django:
In `settings.py`:
```python
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 the [Upgrading templates documentation](https://docs.djangoproject.com/en/stable/ref/templates/upgrading/).
In `yourapp/jinja2.py`:
```python
# Include this for Python 2.
from __future__ import absolute_import
from jinja2 import Environment
def environment(**kwargs):
extensions = [] if 'extensions' not in kwargs else kwargs['extensions']
extensions.append('sass_processor.jinja2.ext.SassSrc')
kwargs['extensions'] = extensions
return Environment(**kwargs)
```
If you want to make use of the `compilescss` command, then you will also have to add the following to your settings:
```python
from yourapp.jinja2 import environment
COMPRESS_JINJA2_GET_ENVIRONMENT = environment
```
## Usage
### In your Django templates
```django
{% load sass_tags %}
<link href="{% sass_src 'myapp/css/mystyle.scss' %}" rel="stylesheet" type="text/css" />
```
The above template code will be rendered as HTML
```html
<link href="/static/myapp/css/mystyle.css" rel="stylesheet" type="text/css" />
```
You can safely use this templatetag inside a [Sekizai](https://django-sekizai.readthedocs.io/)'s
`{% addtoblock "css" %}` statement.
### In Media classes or properties
In Python code, you can access the API of the SASS processor directly. This for instance is useful
in Django's admin or form framework.
```python
from sass_processor.processor import sass_processor
class SomeAdminOrFormClass(...):
...
class Media:
css = {
'all': [sass_processor('myapp/css/mystyle.scss')],
}
```
## Add vendor prefixes to CSS rules using values from https://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 install
```shell
npm install -g npx
```
and inside your project root, install
```shell
npm install postcss-cli autoprefixer
```
Check that the path of `node_modules` corresponds to its entry in the settings directive
`STATICFILES_DIRS` (see below).
In case `npx` can not be found in your system path, use the settings directive
`NODE_NPX_PATH = /path/to/npx` to point to that executable.
If everything is setup correctly, **django-sass-processor** adds all required vendor prefixes to
the compiled CSS files. For further information, refer to the
[Autoprefixer](https://github.com/postcss/autoprefixer) package.
To disable autoprefixing, set `NODE_NPX_PATH = None`.
**Important note**: If `npx` is installed, but `postcss` and/or `autoprefixer` are missing
in the local `node_modules`, setting `NODE_NPX_PATH` to `None` is manadatory, otherwise
**django-sass-processor** does not know how to postprocess the generated CSS files.
## Offline compilation
If you want to precompile all occurrences of your SASS/SCSS files for the whole project, on the
command line invoke:
```shell
./manage.py compilescss
```
This is useful for preparing production environments, where SASS/SCSS files can't be compiled on
the fly.
To simplify the deployment, the compiled `*.css` files are stored side-by-side with their
corresponding SASS/SCSS files. After compiling the files run
```shell
./manage.py collectstatic
```
as you would in a normal deployment.
In case you don't want to expose the SASS/SCSS files in a production environment,
deploy with:
```shell
./manage.py collectstatic --ignore=*.scss
```
To get rid of the compiled `*.css` files in your local static directories, simply reverse the
above command:
```shell
./manage.py compilescss --delete-files
```
This will remove all occurrences of previously generated `*.css` files.
Or you may compile results to the `STORAGES['sass_processor']['ROOT']` [Django >= 4.2.*] or `SASS_PROCESSOR_ROOT`
[Django <= 4.1.*] directory directy (if not specified - to
`STATIC_ROOT`):
```shell
./manage.py compilescss --use-storage
```
Combine with `--delete-files` switch to purge results from there.
If you use an alternative templating engine set its name in `--engine` argument. Currently
`django` and `jinja2` are supported, see
[django-compressor documentation](http://django-compressor.readthedocs.org/en/latest/) on how to
set up `COMPRESS_JINJA2_GET_ENVIRONMENT` to configure jinja2 engine support.
During offline compilation **django-sass-processor** parses all Python files and looks for
invocations of `sass_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 templates
By default, **django-sass-processor** will locate SASS/SCSS files from .html templates,
but you can extend or override this behavior in your settings with:
```python
SASS_TEMPLATE_EXTS = ['.html','.jade']
```
## Configure SASS variables through settings.py
In SASS, a nasty problem is to set the correct include paths for icons and fonts. Normally this is
done through a `_variables.scss` file, but this inhibits a configuration through your projects
`settings.py`.
To avoid the need for duplicate configuration settings, **django-sass-processor** offers a SASS
function to fetch any arbitrary configuration directive from the project's `settings.py`. This
is specially handy to set the include path of your Glyphicons font directory. Assume, Bootstrap-SASS
has been installed using:
```shell
npm install bootstrap-sass
```
then locate the directory named `node_modules` and add it to your settings, so that your fonts are
accessible through the Django's `django.contrib.staticfiles.finders.FileSystemFinder`:
```python
STATICFILES_DIRS = [
...
('node_modules', '/path/to/your/project/node_modules/'),
...
]
NODE_MODULES_URL = STATIC_URL + 'node_modules/'
```
With the SASS function `get-setting`, it is possible to override any SASS variable with a value
configured in the project's `settings.py`. For the Glyphicons font search path, add this to your
`_variables.scss`:
```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 functions
It is even possible to call Python functions from inside any module. Do this by adding
`SASS_PROCESSOR_CUSTOM_FUNCTIONS` to the project's `settings.py`. This shall contain a mapping
of SASS function names pointing to a Python function name.
Example:
```python
SASS_PROCESSOR_CUSTOM_FUNCTIONS = {
'get-color': 'myproject.utils.get_color',
}
```
This allows to invoke Python functions out of any `*.scss` file.
```scss
$color: get-color(250, 10, 120);
```
Here we pass the parameters '250, 10, 120' into the function `def get_color(red, green, blue)`
in Python module `myproject.utils`. Note that this function receives the values as `sass.Number`,
hence extract values using `red.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 type `sass.SassNumber`. For other types, refer to their
documentation.
Such customized functions must accept parameters explicilty, otherwise `sass_processor` does not
know how to map them. Variable argument lists therefore can not be used.
## Error reporting
Whenever **django-sass-processor** runs in debug mode and fails to compile a SASS/SCSS file, it
raises a `sass.CompileError` exception. 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 variable `SASS_PROCESSOR_FAIL_SILENTLY`.
If it is set to `True`, instead of raising that exception, the compilation error message is send
to the Django logger.
## Using other storage backends for compiled CSS files
Under the hood, SASS processor will use any storage configured in your settings as `STORAGES['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 in `STORAGES['sass_processor']['BACKEND']`. You can also
configure a dictionary with options that will be passed to the storage class as keyword arguments
in `STORAGES['sass_processor']['OPTIONS']` [Django >= 4.2.*] or `SASS_PROCESSOR_STORAGE_OPTIONS` [Django <= 4.1.*>]
(e.g. if you want to use `FileSystemStorage`, but with a different `location` or `base_url`:
```python
# 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 Storage
Using the S3 storage backend from [django-storages](https://django-storages.readthedocs.io/en/latest/)
with its regular configuration (if you do not otherwise use it for service static files):
```python
# For Django >= 4.2.*
STORAGES['sass_processor'] = {
'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage'
}
# For Django <= 4.1.*
SASS_PROCESSOR_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
```
## Heroku
If you are deploying to [Heroku](https://www.heroku.com/), use the
[heroku-buildpack-django-sass](https://elements.heroku.com/buildpacks/drpancake/heroku-buildpack-django-sass)
buildpack to automatically compile scss for you.
## Development
To run the tests locally, clone the repository, and, in your local copy, create a new virtualenv.
these commands:
```shell
python -m pip install --upgrade pip
pip install Django
pip install -r tests/requirements.txt
python -m pytest tests
```
Raw data
{
"_id": null,
"home_page": "https://github.com/jrief/django-sass-processor",
"name": "django-sass-processor",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": "django, sass",
"author": "Jacob Rief",
"author_email": "jacob.rief@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/bd/03/1c86386794a462910daf84e9b562b37bd5475d9bd2b37fb676377f63101b/django_sass_processor-1.4.1.tar.gz",
"platform": null,
"description": "# django-sass-processor\n\nAnnoyed having to run a Compass, Grunt or Gulp daemon while developing Django projects?\n\nWell, then this app is for you! Compile SASS/SCSS files on the fly without having to manage\nthird party services nor special IDE plugins.\n\n[![Build Status](https://github.com/jrief/django-sass-processor/actions/workflows/tests.yml/badge.svg)](https://github.com/jrief/django-sass-processor/actions)\n[![PyPI](https://img.shields.io/pypi/pyversions/django-sass-processor.svg)]()\n[![PyPI version](https://img.shields.io/pypi/v/django-sass-processor.svg)](https://pypi.python.org/pypi/django-sass-processor)\n[![PyPI](https://img.shields.io/pypi/l/django-sass-processor.svg)]()\n[![Downloads](https://img.shields.io/pypi/dm/django-sass-processor.svg)](https://pypi.python.org/pypi/django-sass-processor)\n[![Twitter Follow](https://img.shields.io/twitter/follow/shields_io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/jacobrief)\n\n\n## Other good reasons for using this library\n\n* Refer SASS/SCSS files directly from your sources, instead of referring a compiled CSS file,\nhaving to rely on another utility which creates them from SASS/SCSS files, hidden in\nyour source tree.\n* Use Django's `settings.py` for the configuration of paths, box sizes etc., instead of having another\nSCSS specific file (typically `_variables.scss`), to hold these.\n* Extend your SASS functions by calling Python functions directly out of your Django project.\n* View SCSS errors directly in the debug console of your Django's development server.\n\n**django-sass-processor** converts `*.scss` or `*.sass` files into `*.css` while rendering\ntemplates. For performance reasons this is done only once, since the preprocessor keeps track on\nthe timestamps and only recompiles, if any of the imported SASS/SCSS files is younger than the\ncorresponding generated CSS file.\n\n## Introduction\n\nThis Django app provides a templatetag `{% sass_src 'path/to/file.scss' %}`, which can be used\ninstead of the built-in templatetag `static`. This templatetag also works inside Jinja2 templates.\n\nIf SASS/SCSS files shall be referenced through the `Media` class, or `media` property, the SASS\nprocessor can be used directly.\n\nAdditionally, **django-sass-processor** is shipped with a management command, which can convert\nthe content of all occurrences inside the templatetag `sass_src` as an offline operation. Hence\nthe **libsass** compiler is not required in a production environment.\n\nDuring development, a [sourcemap](https://developer.chrome.com/devtools/docs/css-preprocessors) is\ngenerated along side with the compiled `*.css` file. This allows to debug style sheet errors much\neasier.\n\nWith this tool, you can safely remove your Ruby installations \"Compass\" and \"SASS\" from your Django\nprojects. You neither need any directory \"watching\" daemons based on node.js.\n\n## Project's Home\n\nOn GitHub:\n\nhttps://github.com/jrief/django-sass-processor\n\nPlease use the issue tracker to report bugs or propose new features.\n\n## Installation\n\n```\npip install libsass django-compressor django-sass-processor\n```\n\n`django-compressor` is required only for offline compilation, when using the command\n`manage.py compilescss`.\n\n`libsass` is not required on the production environment, if SASS/SCSS files have been precompiled\nand deployed using offline compilation.\n\n## Configuration\n\nIn `settings.py` add to:\n\n```python\nINSTALLED_APPS = [\n ...\n 'sass_processor',\n ...\n]\n```\n\n**django-sass-processor** is shipped with a special finder, to locate the generated `*.css` files\nin the directory referred by `STORAGES['sass_processor']['ROOT']` (for Django >= 4.2.*) or \n`SASS_PROCESSOR_ROOT` (for Django <= 4.1.*), or, if unset `STATIC_ROOT`. Just add it to\nyour `settings.py`. If there is no `STATICFILES_FINDERS` in your `settings.py` don't forget\nto include the **Django** [default finders](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-STATICFILES_FINDERS).\n\n```python\nSTATICFILES_FINDERS = [\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'sass_processor.finders.CssFinder',\n ...\n]\n```\n\nOptionally, add a list of additional search paths, the SASS compiler may examine when using the\n`@import \"...\";` statement in SASS/SCSS files:\n\n```python\nimport os\n\nSASS_PROCESSOR_INCLUDE_DIRS = [\n os.path.join(PROJECT_PATH, 'extra-styles/scss'),\n os.path.join(PROJECT_PATH, 'node_modules'),\n]\n```\n\nAdditionally, **django-sass-processor** will traverse all installed Django apps (`INSTALLED_APPS`)\nand look into their static folders. If any of them contain a file matching the regular expression\npattern `^_.+\\.(scss|sass)$` (read: filename starts with an underscore and is of type `scss` or\n`sass`), then that app specific static folder is added to the **libsass** include dirs. This\nfeature can be disabled in your settings with:\n\n```python\nSASS_PROCESSOR_AUTO_INCLUDE = False\n```\n\nIf inside of your SASS/SCSS files, you also want to import (using `@import \"path/to/scssfile\";`)\nfiles which do not start with an underscore, then you can configure another Regex pattern in your\nsettings, for instance:\n\n```python\nSASS_PROCESSOR_INCLUDE_FILE_PATTERN = r'^.+\\.scss$'\n```\n\nwill look for all files of type `scss`. Remember that SASS/SCSS files which start with an\nunderscore, are intended to be imported by other SASS/SCSS files, while files starting with a\nletter or number are intended to be included by the HTML tag\n`<link href=\"{% sass_src 'path/to/file.scss' %}\" ...>`.\n\nDuring development, or when `SASS_PROCESSOR_ENABLED = True`, the compiled file is placed into the\nfolder referenced by `STORAGES['sass_processor']['ROOT']` (for Django >= 4.2.*) or `SASS_PROCESSOR_ROOT` (for Django <= 4.1.*).\nIf unset, this setting defaults to `STATIC_ROOT`.\nHaving a location outside of the working directory prevents to pollute your local `static/css/...`\ndirectories with auto-generated files. Therefore assure, that this directory is writable by the\nDjango runserver.\n\n\n#### Fine tune SASS compiler parameters in `settings.py`.\n\nInteger `SASS_PRECISION` sets floating point precision for output css. libsass'\ndefault is `5`. Note: **bootstrap-sass** requires `8`, otherwise various\nlayout problems _will_ occur.\n\n```python\nSASS_PRECISION = 8\n```\n\n`SASS_OUTPUT_STYLE` sets coding style of the compiled result, one of `compact`,\n`compressed`, `expanded`, or `nested`. Default is `nested` for `DEBUG`\nand `compressed` in production.\n\nNote: **libsass-python** 0.8.3 has [problem encoding result while saving on\nWindows](https://github.com/dahlia/libsass-python/pull/82), the issue is already\nfixed and will be included in future `pip` package release, in the meanwhile\navoid `compressed` output style.\n\n```python\nSASS_OUTPUT_STYLE = 'compact'\n```\n\n### Jinja2 support\n\n`sass_processor.jinja2.ext.SassSrc` is a Jinja2 extension. Add it to your Jinja2 environment to enable the tag `sass_src`, there is no need for a `load` tag. Example of how to add your Jinja2 environment to Django:\n\nIn `settings.py`:\n\n```python\nTEMPLATES = [{\n 'BACKEND': 'django.template.backends.jinja2.Jinja2',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'environment': 'yourapp.jinja2.environment'\n },\n ...\n}]\n```\n\nMake sure to add the default template backend, if you're still using Django templates elsewhere.\nThis is covered in the [Upgrading templates documentation](https://docs.djangoproject.com/en/stable/ref/templates/upgrading/).\n\nIn `yourapp/jinja2.py`:\n\n```python\n# Include this for Python 2.\nfrom __future__ import absolute_import\n\nfrom jinja2 import Environment\n\n\ndef environment(**kwargs):\n extensions = [] if 'extensions' not in kwargs else kwargs['extensions']\n extensions.append('sass_processor.jinja2.ext.SassSrc')\n kwargs['extensions'] = extensions\n\n return Environment(**kwargs)\n```\n\nIf you want to make use of the `compilescss` command, then you will also have to add the following to your settings:\n\n```python\nfrom yourapp.jinja2 import environment\n\nCOMPRESS_JINJA2_GET_ENVIRONMENT = environment\n```\n\n\n## Usage\n\n### In your Django templates\n\n```django\n{% load sass_tags %}\n\n<link href=\"{% sass_src 'myapp/css/mystyle.scss' %}\" rel=\"stylesheet\" type=\"text/css\" />\n```\n\nThe above template code will be rendered as HTML\n\n```html\n<link href=\"/static/myapp/css/mystyle.css\" rel=\"stylesheet\" type=\"text/css\" />\n```\n\nYou can safely use this templatetag inside a [Sekizai](https://django-sekizai.readthedocs.io/)'s\n`{% addtoblock \"css\" %}` statement.\n\n### In Media classes or properties\n\nIn Python code, you can access the API of the SASS processor directly. This for instance is useful\nin Django's admin or form framework.\n\n```python\nfrom sass_processor.processor import sass_processor\n\nclass SomeAdminOrFormClass(...):\n ...\n class Media:\n css = {\n 'all': [sass_processor('myapp/css/mystyle.scss')],\n }\n```\n\n## Add vendor prefixes to CSS rules using values from https://caniuse.com/\n\nWriting SCSS shall be fast and easy and you should not have to care, whether to add vendor specific\nprefixes to your CSS directives. Unfortunately there is no pure Python package to solve this, but\nwith a few node modules, we can add this to our process chain.\n\nAs superuser install\n\n```shell\nnpm install -g npx\n```\n\nand inside your project root, install\n\n```shell\nnpm install postcss-cli autoprefixer\n```\n\nCheck that the path of `node_modules` corresponds to its entry in the settings directive\n`STATICFILES_DIRS` (see below).\n\nIn case `npx` can not be found in your system path, use the settings directive\n`NODE_NPX_PATH = /path/to/npx` to point to that executable.\n\nIf everything is setup correctly, **django-sass-processor** adds all required vendor prefixes to\nthe compiled CSS files. For further information, refer to the\n[Autoprefixer](https://github.com/postcss/autoprefixer) package.\n\nTo disable autoprefixing, set `NODE_NPX_PATH = None`.\n\n**Important note**: If `npx` is installed, but `postcss` and/or `autoprefixer` are missing\nin the local `node_modules`, setting `NODE_NPX_PATH` to `None` is manadatory, otherwise\n**django-sass-processor** does not know how to postprocess the generated CSS files.\n\n## Offline compilation\n\nIf you want to precompile all occurrences of your SASS/SCSS files for the whole project, on the\ncommand line invoke:\n\n```shell\n./manage.py compilescss\n```\n\nThis is useful for preparing production environments, where SASS/SCSS files can't be compiled on\nthe fly.\n\nTo simplify the deployment, the compiled `*.css` files are stored side-by-side with their\ncorresponding SASS/SCSS files. After compiling the files run\n\n```shell\n./manage.py collectstatic\n```\n\nas you would in a normal deployment.\n\nIn case you don't want to expose the SASS/SCSS files in a production environment,\ndeploy with:\n\n```shell\n./manage.py collectstatic --ignore=*.scss\n```\n\nTo get rid of the compiled `*.css` files in your local static directories, simply reverse the\nabove command:\n\n```shell\n./manage.py compilescss --delete-files\n```\n\nThis will remove all occurrences of previously generated `*.css` files.\n\nOr you may compile results to the `STORAGES['sass_processor']['ROOT']` [Django >= 4.2.*] or `SASS_PROCESSOR_ROOT` \n[Django <= 4.1.*] directory directy (if not specified - to\n`STATIC_ROOT`):\n\n```shell\n./manage.py compilescss --use-storage\n```\n\nCombine with `--delete-files` switch to purge results from there.\n\nIf you use an alternative templating engine set its name in `--engine` argument. Currently\n`django` and `jinja2` are supported, see\n[django-compressor documentation](http://django-compressor.readthedocs.org/en/latest/) on how to\nset up `COMPRESS_JINJA2_GET_ENVIRONMENT` to configure jinja2 engine support.\n\nDuring offline compilation **django-sass-processor** parses all Python files and looks for\ninvocations of `sass_processor('path/to/sassfile.scss')`. Therefore the string specifying\nthe filename must be hard coded and shall not be concatenated or being somehow generated.\n\n### Alternative templates\n\nBy default, **django-sass-processor** will locate SASS/SCSS files from .html templates,\nbut you can extend or override this behavior in your settings with:\n\n```python\nSASS_TEMPLATE_EXTS = ['.html','.jade']\n```\n\n## Configure SASS variables through settings.py\n\nIn SASS, a nasty problem is to set the correct include paths for icons and fonts. Normally this is\ndone through a `_variables.scss` file, but this inhibits a configuration through your projects\n`settings.py`.\n\nTo avoid the need for duplicate configuration settings, **django-sass-processor** offers a SASS\nfunction to fetch any arbitrary configuration directive from the project's `settings.py`. This\nis specially handy to set the include path of your Glyphicons font directory. Assume, Bootstrap-SASS\nhas been installed using:\n\n```shell\nnpm install bootstrap-sass\n```\n\nthen locate the directory named `node_modules` and add it to your settings, so that your fonts are\naccessible through the Django's `django.contrib.staticfiles.finders.FileSystemFinder`:\n\n```python\nSTATICFILES_DIRS = [\n ...\n ('node_modules', '/path/to/your/project/node_modules/'),\n ...\n]\n\nNODE_MODULES_URL = STATIC_URL + 'node_modules/'\n```\n\nWith the SASS function `get-setting`, it is possible to override any SASS variable with a value\nconfigured in the project's `settings.py`. For the Glyphicons font search path, add this to your\n`_variables.scss`:\n\n```scss\n$icon-font-path: unquote(get-setting(NODE_MODULES_URL) + \"bootstrap-sass/assets/fonts/bootstrap/\");\n```\n\nand `@import \"variables\";` whenever you need Glyphicons. You then can safely remove any font\nreferences, such as `<link href=\"/path/to/your/fonts/bootstrap/glyphicons-whatever.ttf\" ...>`\nfrom you HTML templates.\n\n\n### Configure SASS variables through Python functions\n\nIt is even possible to call Python functions from inside any module. Do this by adding\n`SASS_PROCESSOR_CUSTOM_FUNCTIONS` to the project's `settings.py`. This shall contain a mapping\nof SASS function names pointing to a Python function name.\n\nExample:\n\n```python\nSASS_PROCESSOR_CUSTOM_FUNCTIONS = {\n 'get-color': 'myproject.utils.get_color',\n}\n```\n\nThis allows to invoke Python functions out of any `*.scss` file. \n\n```scss\n$color: get-color(250, 10, 120);\n```\n\nHere we pass the parameters '250, 10, 120' into the function `def get_color(red, green, blue)`\nin Python module `myproject.utils`. Note that this function receives the values as `sass.Number`,\nhence extract values using `red.value`, etc.\n\nIf one of these customoized functions returns a value, which is not a string, then convert it\neither to a Python string or to a value of type `sass.SassNumber`. For other types, refer to their\ndocumentation.\n\nSuch customized functions must accept parameters explicilty, otherwise `sass_processor` does not\nknow how to map them. Variable argument lists therefore can not be used.\n\n\n## Error reporting\n\nWhenever **django-sass-processor** runs in debug mode and fails to compile a SASS/SCSS file, it\nraises a `sass.CompileError` exception. This shows the location of the error directly on the\nDjango debug console and is very useful during development.\n\nThis behaviour can be overridden using the settings variable `SASS_PROCESSOR_FAIL_SILENTLY`.\nIf it is set to `True`, instead of raising that exception, the compilation error message is send\nto the Django logger.\n\n\n## Using other storage backends for compiled CSS files\n\nUnder the hood, SASS processor will use any storage configured in your settings as `STORAGES['staticfiles']`.\nThis means you can use anything you normally use for serving static files, e.g. S3.\n\nA custom Storage class can be used if your deployment needs to serve generated CSS files from elsewhere,\ne.g. when your static files storage is not writable at runtime and you nede to re-compile CSS\nin production. To use a custom storage, configure it in `STORAGES['sass_processor']['BACKEND']`. You can also\nconfigure a dictionary with options that will be passed to the storage class as keyword arguments\nin `STORAGES['sass_processor']['OPTIONS']` [Django >= 4.2.*] or `SASS_PROCESSOR_STORAGE_OPTIONS` [Django <= 4.1.*>] \n(e.g. if you want to use `FileSystemStorage`, but with a different `location` or `base_url`:\n\n```python\n# For Django >= 4.2.*\nSTORAGES['sass_processor'] = {\n 'BACKEND': 'django.core.files.storage.FileSystemStorage',\n 'OPTIONS': {\n 'location': '/srv/media/generated',\n 'base_url': 'https://media.myapp.example.com/generated'\n }\n}\n\n# For Django <= 4.1.*\nSASS_PROCESSOR_STORAGE = 'django.core.files.storage.FileSystemStorage'\nSASS_PROCESSOR_STORAGE_OPTIONS = {\n 'location': '/srv/media/generated',\n 'base_url': 'https://media.myapp.example.com/generated'\n}\n```\n\n\n### Amazon's S3 Storage\n\nUsing the S3 storage backend from [django-storages](https://django-storages.readthedocs.io/en/latest/)\nwith its regular configuration (if you do not otherwise use it for service static files):\n\n```python\n# For Django >= 4.2.*\nSTORAGES['sass_processor'] = {\n 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage'\n}\n\n# For Django <= 4.1.*\nSASS_PROCESSOR_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'\n```\n\n\n## Heroku\n\nIf you are deploying to [Heroku](https://www.heroku.com/), use the\n[heroku-buildpack-django-sass](https://elements.heroku.com/buildpacks/drpancake/heroku-buildpack-django-sass)\nbuildpack to automatically compile scss for you.\n\n\n## Development\n\nTo run the tests locally, clone the repository, and, in your local copy, create a new virtualenv.\nthese commands:\n\n```shell\npython -m pip install --upgrade pip\npip install Django\npip install -r tests/requirements.txt\npython -m pytest tests\n```\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "SASS processor to compile SCSS files into *.css, while rendering, or offline.",
"version": "1.4.1",
"project_urls": {
"Homepage": "https://github.com/jrief/django-sass-processor"
},
"split_keywords": [
"django",
" sass"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "e09a926059d7b82f79a6e90cb3c98382c763ed14ff1e395ca0cf988d1a6cf6c2",
"md5": "077fac723f89551979dd4363092656ad",
"sha256": "7b76560172f72519cfcda944feeb517b37f40f5562196298245f5569c2d02f91"
},
"downloads": -1,
"filename": "django_sass_processor-1.4.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "077fac723f89551979dd4363092656ad",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 20535,
"upload_time": "2024-05-29T13:59:54",
"upload_time_iso_8601": "2024-05-29T13:59:54.860101Z",
"url": "https://files.pythonhosted.org/packages/e0/9a/926059d7b82f79a6e90cb3c98382c763ed14ff1e395ca0cf988d1a6cf6c2/django_sass_processor-1.4.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "bd031c86386794a462910daf84e9b562b37bd5475d9bd2b37fb676377f63101b",
"md5": "a54bd1b7f7f8a79bef20e21a78cd6c4c",
"sha256": "1e9d04769f76d89bbf77b9b279ba83dfacad9c98c03ca8a58ecfc29d997e6fcf"
},
"downloads": -1,
"filename": "django_sass_processor-1.4.1.tar.gz",
"has_sig": false,
"md5_digest": "a54bd1b7f7f8a79bef20e21a78cd6c4c",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 20096,
"upload_time": "2024-05-29T13:59:56",
"upload_time_iso_8601": "2024-05-29T13:59:56.970757Z",
"url": "https://files.pythonhosted.org/packages/bd/03/1c86386794a462910daf84e9b562b37bd5475d9bd2b37fb676377f63101b/django_sass_processor-1.4.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-05-29 13:59:56",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "jrief",
"github_project": "django-sass-processor",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "django-sass-processor"
}