Included Filters¶
The following filters are included in webassets
, though some may
require the installation of an external library, or the availability of
external tools.
You can also write custom filters.
Javascript cross-compilers¶
-
class
webassets.filter.babel.
Babel
(**kwargs)¶ Processes ES6+ code into ES5 friendly code using Babel.
Requires the babel executable to be available externally. To install it, you might be able to do:
$ npm install --global babel-cli
You probably also want some presets:
$ npm install --global babel-preset-es2015
Example python bundle:
es2015 = get_filter('babel', presets='es2015') bundle = Bundle('**/*.js', filters=es2015)
Example YAML bundle:
es5-bundle: output: dist/es5.js config: BABEL_PRESETS: es2015 filters: babel contents: - file1.js - file2.js
Supported configuration options:
- BABEL_BIN
- The path to the babel binary. If not set the filter will try to run
babel
as if it’s in the system path. - BABEL_PRESETS
- Passed straight through to
babel --presets
to specify which babel presets to use - BABEL_EXTRA_ARGS
- A list of manual arguments to be specified to the babel command
- BABEL_RUN_IN_DEBUG
- May be set to False to make babel not run in debug
Javascript compressors¶
rjsmin
¶
-
class
webassets.filter.rjsmin.
RJSMin
(**kwargs)¶ Minifies Javascript by removing whitespace, comments, etc.
Uses the rJSmin library, which is included with webassets. However, if you have the external package installed, it will be used instead. You may want to do this to get access to the faster C-extension.
Supported configuration options:
- RJSMIN_KEEP_BANG_COMMENTS (boolean)
- Keep bang-comments (comments starting with an exclamation mark).
yui_js
¶
Minify Javascript and CSS with YUI Compressor.
YUI Compressor is an external tool written in Java, which needs to be available. One way to get it is to install the yuicompressor package:
pip install yuicompressor
No configuration is necessary in this case.
You can also get YUI compressor a different way and define
a YUI_COMPRESSOR_PATH
setting that points to the .jar
file.
Otherwise, an environment variable by the same name is tried. The
filter will also look for a JAVA_HOME
environment variable to
run the .jar
file, or will otherwise assume that java
is
on the system path.
-
class
webassets.filter.yui.
YUIJS
(**kwargs)¶
closure_js
¶
Minify Javascript with Google Closure Compiler.
Google Closure Compiler is an external tool written in Java, which needs to be available. One way to get it is to install the closure package:
pip install closure
No configuration is necessary in this case.
You can also define a CLOSURE_COMPRESSOR_PATH
setting that
points to the .jar
file. Otherwise, an environment variable by
the same name is tried. The filter will also look for a JAVA_HOME
environment variable to run the .jar
file, or will otherwise
assume that java
is on the system path.
Supported configuration options:
- CLOSURE_COMPRESSOR_OPTIMIZATION
- Corresponds to Google Closure’s compilation level parameter.
- CLOSURE_EXTRA_ARGS
A list of further options to be passed to the Closure compiler. There are a lot of them.
For options which take values you want to use two items in the list:
['--output_wrapper', 'foo: %output%']
uglifyjs
¶
-
class
webassets.filter.uglifyjs.
UglifyJS
(**kwargs)¶ Minify Javascript using UglifyJS.
The filter requires version 2 of UglifyJS.
UglifyJS is an external tool written for NodeJS; this filter assumes that the
uglifyjs
executable is in the path. Otherwise, you may define aUGLIFYJS_BIN
setting.Additional options may be passed to
uglifyjs
using the settingUGLIFYJS_EXTRA_ARGS
, which expects a list of strings.
jsmin
¶
-
class
webassets.filter.jsmin.
JSMin
(**kwargs)¶ Minifies Javascript by removing whitespace, comments, etc.
This filter uses a Python port of Douglas Crockford’s JSMin, which needs to be installed separately.
There are actually multiple implementations available, for example one by Baruch Even. Easiest to install via PyPI is the one by Dave St. Germain:
$ pip install jsmin
The filter is tested with this
jsmin
package from PyPI, but will work with any module that exposes aJavascriptMinify
object with aminify
method.If you want to avoid installing another dependency, use the
webassets.filter.rjsmin.RJSMin
filter instead.
jspacker
¶
-
class
webassets.filter.jspacker.
JSPacker
(**kwargs)¶ Reduces the size of Javascript using an inline compression algorithm, i.e. the script will be unpacked on the client side by the browser.
Based on Dean Edwards’ jspacker 2, as ported by Florian Schulze.
slimit
¶
-
class
webassets.filter.slimit.
Slimit
(**kwargs)¶ Minifies JS.
Requires the
slimit
package (https://github.com/rspivak/slimit), which is a JavaScript minifier written in Python. It compiles JavaScript into more compact code so that it downloads and runs faster.It offers mangle and mangle_toplevel options through SLIMIT_MANGLE and SLIMIT_MANGLE_TOPLEVEL
CSS compressors¶
cssmin
¶
-
class
webassets.filter.cssmin.
CSSMin
(**kwargs)¶ Minifies CSS.
Requires the
cssmin
package (http://github.com/zacharyvoase/cssmin), which is a port of the YUI CSS compression algorithm.
cssutils
¶
cleancss
¶
-
class
webassets.filter.cleancss.
CleanCSS
(**kwargs)¶ Minify css using Clean-css.
Clean-css is an external tool written for NodeJS; this filter assumes that the
cleancss
executable is in the path. Otherwise, you may define aCLEANCSS_BIN
setting.Additional options may be passed to
cleancss
binary using the settingCLEANCSS_EXTRA_ARGS
, which expects a list of strings.
slimmer_css
¶
rcssmin
¶
-
class
webassets.filter.rcssmin.
RCSSMin
(**kwargs)¶ Minifies CSS.
Requires the
rcssmin
package (https://github.com/ndparker/rcssmin). Alike ‘cssmin’ it is a port of the YUI CSS compression algorithm but aiming for speed instead of maximum compression.Supported configuration options: RCSSMIN_KEEP_BANG_COMMENTS (boolean)
Keep bang-comments (comments starting with an exclamation mark).
JS/CSS compilers¶
postcss
¶
-
class
webassets.filter.postcss.
PostCSS
(**kwargs)¶ Processes CSS code using PostCSS.
Requires the
postcss
executable to be available externally. To install it, you might be able to do:$ npm install --global postcss
You should also install the plugins you want to use:
$ npm install --global postcss-cssnext
You can configure postcss in
postcss.config.js
:module.exports = { plugins: [ require('postcss-cssnext')({ // optional configuration for cssnext }) ], };
Supported configuration options:
- POSTCSS_BIN
- Path to the postcss executable used to compile source files. By
default, the filter will attempt to run
postcss
via the system path. - POSTCSS_EXTRA_ARGS
- Additional command-line options to be passed to
postcss
using this setting, which expects a list of strings.
clevercss
¶
less
¶
-
class
webassets.filter.less.
Less
(**kwargs)¶ Converts less markup to real CSS.
This depends on the NodeJS implementation of less, installable via npm. To use the old Ruby-based version (implemented in the 1.x Ruby gem), see
Less
.Supported configuration options:
- LESS_BIN (binary)
- Path to the less executable used to compile source files. By default,
the filter will attempt to run
lessc
via the system path. - LESS_LINE_NUMBERS (line_numbers)
- Outputs filename and line numbers. Can be either ‘comments’, which will output the debug info within comments, ‘mediaquery’ that will output the information within a fake media query which is compatible with the SASSPath to the less executable used to compile source files.
- LESS_RUN_IN_DEBUG (run_in_debug)
- By default, the filter will compile in debug mode. Since the less
compiler is written in Javascript and capable of running in the
browser, you can set this to
False
to have your original less source files served (see below). - LESS_PATHS (paths)
- Add include paths for less command line. It should be a list of paths relatives to Environment.directory or absolute paths. Order matters as less will pick the first file found in path order.
- LESS_AS_OUTPUT (boolean)
By default, this works as an “input filter”, meaning
less
is called for each source file in the bundle. This is because the path of the source file is required so that @import directives within the Less file can be correctly resolved.However, it is possible to use this filter as an “output filter”, meaning the source files will first be concatenated, and then the Less filter is applied in one go. This can provide a speedup for bigger projects.
Compiling less in the browser
less is an interesting case because it is written in Javascript and capable of running in the browser. While for performance reason you should prebuild your stylesheets in production, while developing you may be interested in serving the original less files to the client, and have less compile them in the browser.
To do so, you first need to make sure the less filter is not applied when
Environment.debug
isTrue
. You can do so via an option:env.config['less_run_in_debug'] = False
Second, in order for the less to identify the less source files as needing to be compiled, they have to be referenced with a
rel="stylesheet/less"
attribute. One way to do this is to use theBundle.extra
dictionary, which works well with the template tags that webassets provides for some template languages:less_bundle = Bundle( '**/*.less', filters='less', extra={'rel': 'stylesheet/less' if env.debug else 'stylesheet'} )
Then, for example in a Jinja2 template, you would write:
{% assets less_bundle %} <link rel="{{ EXTRA.rel }}" type="text/css" href="{{ ASSET_URL }}"> {% endassets %}
With this, the
<link>
tag will sport the correctrel
value both in development and in production.Finally, you need to include the less compiler:
if env.debug: js_bundle.contents += 'http://lesscss.googlecode.com/files/less-1.3.0.min.js'
less_ruby
¶
-
class
webassets.filter.less_ruby.
Less
(**kwargs)¶ Converts Less markup to real CSS.
This uses the old Ruby implementation available in the 1.x versions of the less gem. All 2.x versions of the gem are wrappers around the newer NodeJS/Javascript implementation, which you are generally encouraged to use, and which is available in webassets via the
Less
filter.This filter for the Ruby version is being kept around for backwards-compatibility.
Supported configuration options:
- LESS_RUBY_PATH (binary)
- Path to the less executable used to compile source files. By default,
the filter will attempt to run
lessc
via the system path.
sass
¶
-
class
webassets.filter.sass.
Sass
(**kwargs)¶ Converts Sass markup to real CSS.
Requires the Sass executable to be available externally. To install it, you might be able to do:
$ sudo gem install sass
By default, this works as an “input filter”, meaning
sass
is called for each source file in the bundle. This is because the path of the source file is required so that @import directives within the Sass file can be correctly resolved.However, it is possible to use this filter as an “output filter”, meaning the source files will first be concatenated, and then the Sass filter is applied in one go. This can provide a speedup for bigger projects.
To use Sass as an output filter:
from webassets.filter import get_filter sass = get_filter('sass', as_output=True) Bundle(...., filters=(sass,))
However, if you want to use the output filter mode and still also use the @import directive in your Sass files, you will need to pass along the
load_paths
argument, which specifies the path to which the imports are relative to (this is implemented by changing the working directory before calling thesass
executable):sass = get_filter('sass', as_output=True, load_paths='/tmp')
With
as_output=True
, the resulting concatenation of the Sass files is piped to Sass via stdin (cat ... | sass --stdin ...
) and may cause applications to not compile if import statements are given as relative paths.For example, if a file
foo/bar/baz.scss
imports filefoo/bar/bat.scss
(same directory) and the import is defined as@import "bat";
then Sass will fail compiling because Sass has naturally no information on wherebaz.scss
is located on disk (since the data was passed via stdin) in order for Sass to resolve the location ofbat.scss
:Traceback (most recent call last): ... webassets.exceptions.FilterError: sass: subprocess had error: stderr=(sass):1: File to import not found or unreadable: bat. (Sass::SyntaxError) Load paths: /path/to/project-foo on line 1 of standard input Use --trace for backtrace. , stdout=, returncode=65
To overcome this issue, the full path must be provided in the import statement,
@import "foo/bar/bat"
, then webassets will pass theload_paths
argument (e.g.,/path/to/project-foo
) to Sass via its-I
flags so Sass can resolve the full path to the file to be imported:/path/to/project-foo/foo/bar/bat
Support configuration options:
- SASS_BIN
- The path to the Sass binary. If not set, the filter will
try to run
sass
as if it’s in the system path. - SASS_STYLE
- The style for the output CSS. Can be one of
expanded
(default),nested
,compact
orcompressed
. - SASS_DEBUG_INFO
If set to
True
, will cause Sass to output debug information to be used by the FireSass Firebug plugin. Corresponds to the--debug-info
command line option of Sass.Note that for this, Sass uses
@media
rules, which are not removed by a CSS compressor. You will thus want to make sure that this option is disabled in production.By default, the value of this option will depend on the environment
DEBUG
setting.- SASS_LINE_COMMENTS
Passes
--line-comments
flag to sass which emit comments in the generated CSS indicating the corresponding source line.Note that this option is disabled by Sass if
--style compressed
or--debug-info
options are provided.Enabled by default. To disable, set empty environment variable
SASS_LINE_COMMENTS=
or passline_comments=False
to this filter.- SASS_AS_OUTPUT
By default, this works as an “input filter”, meaning
sass
is called for each source file in the bundle. This is because the path of the source file is required so that @import directives within the Sass file can be correctly resolved.However, it is possible to use this filter as an “output filter”, meaning the source files will first be concatenated, and then the Sass filter is applied in one go. This can provide a speedup for bigger projects.
It will also allow you to share variables between files.
- SASS_SOURCE_MAP
- If provided, this will generate source maps in the output depending
on the type specified. By default this will use Sass’s
auto
. Possible values areauto
,file
,inline
, ornone
. - SASS_LOAD_PATHS
- It should be a list of paths relatives to Environment.directory or absolute paths. Order matters as sass will pick the first file found in path order. These are fed into the -I flag of the sass command and is used to control where sass imports code from.
- SASS_LIBS
- It should be a list of paths relatives to Environment.directory or absolute paths. These are fed into the -r flag of the sass command and is used to require ruby libraries before running sass.
scss
¶
-
class
webassets.filter.sass.
SCSS
(*a, **kw)¶ Version of the
sass
filter that uses the SCSS syntax.
compass
¶
-
class
webassets.filter.compass.
Compass
(**kwargs)¶ Converts Compass .sass files to CSS.
Requires at least version 0.10.
To compile a standard Compass project, you only need to have to compile your main
screen.sass
,print.sass
andie.sass
files. All the partials that you include will be handled by Compass.If you want to combine the filter with other CSS filters, make sure this one runs first.
Supported configuration options:
- COMPASS_BIN
- The path to the Compass binary. If not set, the filter will
try to run
compass
as if it’s in the system path. - COMPASS_PLUGINS
- Compass plugins to use. This is equivalent to the
--require
command line option of the Compass. and expects a Python list object of Ruby libraries to load. - COMPASS_CONFIG
An optional dictionary of Compass configuration options. The values are emitted as strings, and paths are relative to the Environment’s
directory
by default; include aproject_path
entry to override this.The
sourcemap
option has a caveat. A file called _.css.map is created by Compass in the tempdir (where _.scss is the original asset), which is then moved into the output_path directory. Since the tempdir is created one level down from the output path, the relative links in the sourcemap should correctly map. This file, however, will not be versioned, and thus this option should ideally only be used locally for development and not in production with a caching service as the _.css.map file will not be invalidated.
pyscss
¶
-
class
webassets.filter.pyscss.
PyScss
(**kwargs)¶ Converts Scss markup to real CSS.
This uses PyScss, a native Python implementation of the Scss language. The PyScss module needs to be installed. It’s API has been changing; currently, version 1.1.5 is known to be supported.
This is an alternative to using the
sass
orscss
filters, which are based on the original, external tools.Note
The Sass syntax is not supported by PyScss. You need to use the
sass
filter based on the original Ruby implementation instead.Supported configuration options:
- PYSCSS_DEBUG_INFO (debug_info)
Include debug information in the output for use with FireSass.
If unset, the default value will depend on your
Environment.debug
setting.- PYSCSS_LOAD_PATHS (load_paths)
Additional load paths that PyScss should use.
Warning
The filter currently does not automatically use
Environment.load_path
for this.- PYSCSS_STATIC_ROOT (static_root)
- The directory PyScss should look in when searching for include
files that you have referenced. Will use
Environment.directory
by default. - PYSCSS_STATIC_URL (static_url)
- The url PyScss should use when generating urls to files in
PYSCSS_STATIC_ROOT
. Will useEnvironment.url
by default. - PYSCSS_ASSETS_ROOT (assets_root)
- The directory PyScss should look in when searching for things
like images that you have referenced. Will use
PYSCSS_STATIC_ROOT
by default. - PYSCSS_ASSETS_URL (assets_url)
- The url PyScss should use when generating urls to files in
PYSCSS_ASSETS_ROOT
. Will usePYSCSS_STATIC_URL
by default. - PYSCSS_STYLE (style)
- The style of the output CSS. Can be one of
nested
(default),compact
,compressed
, orexpanded
.
libsass
¶
-
class
webassets.filter.libsass.
LibSass
(**kwargs)¶ Converts Sass markup to real CSS.
Requires the
libsass
package (https://pypi.python.org/pypi/libsass):pip install libsass
libsass is binding to C/C++ implementation of a Sass compiler Libsass
Configuration options:
- LIBSASS_STYLE (style)
- an optional coding style of the compiled result. choose one of: nested (default), expanded, compact, compressed
- LIBSASS_INCLUDES (includes)
- an optional list of paths to find @imported SASS/CSS source files
- LIBSASS_AS_OUTPUT
- use this filter as an “output filter”, meaning the source files will first be concatenated, and then the Sass filter is applied.
See libsass documentation for full documentation about these configuration options:
Example:
Define a bundle for
style.scss
that contains@imports
to files in subfolders:Bundle('style.scss', filters='libsass', output='style.css', depends='**/*.scss')
node-sass
¶
-
class
webassets.filter.node_sass.
NodeSass
(**kwargs)¶ Converts Scss markup to real CSS.
This uses node-sass which is a wrapper around libsass.
This is an alternative to using the
sass
orscss
filters, which are based on the original, external tools.Supported configuration options:
- NODE_SASS_DEBUG_INFO (debug_info)
Include debug information in the output
If unset, the default value will depend on your
Environment.debug
setting.- NODE_SASS_LOAD_PATHS (load_paths)
- Additional load paths that node-sass should use.
- NODE_SASS_STYLE (style)
- The style of the output CSS. Can be one of
nested
(default),compact
,compressed
, orexpanded
. - NODE_SASS_CLI_ARGS (cli_args)
- Additional cli arguments
node-scss
¶
-
class
webassets.filter.node_sass.
NodeSCSS
(*a, **kw)¶ Version of the
node-sass
filter that uses the SCSS syntax.
stylus
¶
-
class
webassets.filter.stylus.
Stylus
(**kwargs)¶ Converts Stylus markup to CSS.
Requires the Stylus executable to be available externally. You can install it using the Node Package Manager:
$ npm install -g stylus
Supported configuration options:
- STYLUS_BIN
- The path to the Stylus binary. If not set, assumes
stylus
is in the system path. - STYLUS_PLUGINS
- A Python list of Stylus plugins to use. Each plugin will be included
via Stylus’s command-line
--use
argument. - STYLUS_EXTRA_ARGS
- A Python list of any additional command-line arguments.
- STYLUS_EXTRA_PATHS
- A Python list of any additional import paths.
coffeescript
¶
-
class
webassets.filter.coffeescript.
CoffeeScript
(**kwargs)¶ Converts CoffeeScript to real JavaScript.
If you want to combine it with other JavaScript filters, make sure this one runs first.
Supported configuration options:
- COFFEE_NO_BARE
- Set to
True
to compile with the top-level function wrapper (suppresses the –bare option tocoffee
, which is used by default).
typescript
¶
-
class
webassets.filter.typescript.
TypeScript
(**kwargs)¶ Compile TypeScript to JavaScript.
TypeScript is an external tool written for NodeJS. This filter assumes that the
tsc
executable is in the path. Otherwise, you may define theTYPESCRIPT_BIN
setting.To specify TypeScript compiler options,
TYPESCRIPT_CONFIG
may be defined. E.g.:--removeComments true --target ES6
.
requirejs
¶
-
class
webassets.filter.requirejs.
RequireJSFilter
(**kwargs)¶ Optimizes AMD-style modularized JavaScript into a single asset using RequireJS.
This depends on the NodeJS executable
r.js
; install via npm:$ npm install -g requirejs
Details on configuring r.js can be found at http://requirejs.org/docs/optimization.html#basics.
Supported configuration options:
executable (env: REQUIREJS_BIN)
Path to the RequireJS executable used to compile source files. By default, the filter will attempt to runr.js
via the system path.config (env: REQUIREJS_CONFIG)
The RequireJS options file. The path is taken to be relative to the Environment.directory (by default is /static).baseUrl (env: REQUIREJS_BASEURL)
ThebaseUrl
parameter to r.js; this is the directory that AMD modules will be loaded from. The path is taken relative to the Environment.directory (by default is /static). Typically, this is used in conjunction with abaseUrl
parameter set in the config options file, where the baseUrl value in the config file is used for client-side processing, and the value here is for server-side processing.optimize (env: REQUIREJS_OPTIMIZE)
Theoptimize
parameter to r.js; controls whether or not r.js minifies the output. By default, it is enabled, but can be set tonone
to disable minification. The typical scenario to disable minification is if you do some additional processing of the JavaScript (such as removingconsole.log()
lines) before minification by therjsmin
filter.extras (env: REQUIREJS_EXTRAS)
Any other command-line parameters to be passed to r.js. The string is expected to be in unix shell-style format, meaning that quotes can be used to escape spaces, etc.run_in_debug (env: REQUIREJS_RUN_IN_DEBUG)
Boolean which controls if the AMD requirejs is evaluated client-side or server-side in debug mode. If set to a truthy value (e.g. ‘yes’), then server-side compilation is done, even in debug mode. The default is false.Client-side AMD evaluation
AMD modules can be loaded client-side without any processing done on the server-side. The advantage to this is that debugging is easier because the browser can tell you which source file is responsible for a particular line of code. The disadvantage is that it means that each loaded AMD module is a separate HTTP request. When running client-side, the client needs access to the config – for this reason, when running in client-side mode, the webassets environment must be adjusted to include a reference to this configuration. Typically, this is done by adding something similar to the following during webassets initialization:
if env.debug and not env.config.get('requirejs_run_in_debug', True): env['requirejs'].contents += ('requirejs-browser-config.js',)
And the file
requirejs-browser-config.js
will look something like:require.config({baseUrl: '/static/script/'});
Set the run_in_debug option to control client-side or server-side compilation in debug.
JavaScript templates¶
jst
¶
-
class
webassets.filter.jst.
JST
(**kwargs)¶ This filter processes generic JavaScript templates. It will generate JavaScript code that runs all files through a template compiler, and makes the templates available as an object.
It was inspired by Jammit.
For example, if you have a file named
license.jst
:<div class="drivers-license"> <h2>Name: <%= name %></h2> <em>Hometown: <%= birthplace %></em> </div>
Then, after applying this filter, you could use the template in JavaScript:
JST.license({name : "Moe", birthplace : "Brooklyn"});
The name of each template is derived from the filename. If your JST files are spread over different directories, the path up to the common prefix will be included. For example:
Bundle('templates/app1/license.jst', 'templates/app2/profile.jst', filters='jst')
will make the templates available as
app1/license
andapp2/profile
.Note
The filter is “generic” in the sense that it does not actually compile the templates, but wraps them in a JavaScript function call, and can thus be used with any template language. webassets also has filters for specific JavaScript template languages like
DustJS
orHandlebars
, and those filters precompile the templates on the server, which means a performance boost on the client-side.Unless configured otherwise, the filter will use the same micro-templating language that Jammit uses, which is turn is the same one that is available in underscore.js. The JavaScript code necessary to compile such templates will implicitly be included in the filter output.
Supported configuration options:
- JST_COMPILER (template_function)
A string that is inserted into the generated JavaScript code in place of the function to be called that should do the compiling. Unless you specify a custom function here, the filter will include the JavaScript code of it’s own micro-templating language, which is the one used by underscore.js and Jammit.
If you assign a custom function, it is your responsibility to ensure that it is available in your final JavaScript.
If this option is set to
False
, then the template strings will be output directly, which is to say,JST.foo
will be a string holding the raw source of thefoo
template.- JST_NAMESPACE (namespace)
- How the templates should be made available in JavaScript. Defaults to
window.JST
, which gives you a globalJST
object. - JST_BARE (bare)
Whether everything generated by this filter should be wrapped inside an anonymous function. Default to
False
.Note
If you enable this option, the namespace must be a property of the
window
object, or you won’t be able to access the templates.- JST_DIR_SEPARATOR (separator)
- The separator character to use for templates within directories. Defaults to ‘/’
handlebars
¶
-
class
webassets.filter.handlebars.
Handlebars
(**kwargs)¶ Compile Handlebars templates.
This filter assumes that the
handlebars
executable is in the path. Otherwise, you may define aHANDLEBARS_BIN
setting.Note
Use this filter if you want to precompile Handlebars templates. If compiling them in the browser is acceptable, you may use the JST filter, which needs no external dependency.
Warning
Currently, this filter is not compatible with input filters. Any filters that would run during the input-stage will simply be ignored. Input filters tend to be other compiler-style filters, so this is unlikely to be an issue.
dustjs
¶
-
class
webassets.filter.dust.
DustJS
(**kwargs)¶ DustJS templates compilation filter.
Takes a directory full
.dust
files and creates a single Javascript object that registers to thedust
global when loaded in the browser:Bundle('js/templates/', filters='dustjs')
Note that in the above example, a directory is given as the bundle contents, which is unusual, but required by this filter.
This uses the
dusty
compiler, which is a separate project from the DustJS implementation. To installdusty
together with LinkedIn’s version ofdustjs
(the original does not support NodeJS > 0.4):npm install dusty rm -rf node_modules/dusty/node_modules/dust git clone https://github.com/linkedin/dustjs node_modules/dust
Note
To generate the DustJS client-side Javascript, you can then do:
cd node_modules/dust make dust cp dist/dist-core...js your/static/assets/path
For compilation, set the
DUSTY_PATH=.../node_modules/dusty/bin/dusty
. Optionally, setNODE_PATH=.../node
.
Other¶
cssrewrite
¶
-
class
webassets.filter.cssrewrite.
CSSRewrite
(replace=False)¶ Source filter that rewrites relative urls in CSS files.
CSS allows you to specify urls relative to the location of the CSS file. However, you may want to store your compressed assets in a different place than source files, or merge source files from different locations. This would then break these relative CSS references, since the base URL changed.
This filter transparently rewrites CSS
url()
instructions in the source files to make them relative to the location of the output path. It works as a source filter, i.e. it is applied individually to each source file before they are merged.No configuration is necessary.
The filter also supports a manual mode:
get_filter('cssrewrite', replace={'old_directory':'/custom/path/'})
This will rewrite all urls that point to files within
old_directory
to use/custom/path
as a prefix instead.You may plug in your own replace function:
get_filter('cssrewrite', replace=lambda url: re.sub(r'^/?images/', '/images/', url)) get_filter('cssrewrite', replace=lambda url: '/images/'+url[7:] if url.startswith('images/') else url)
datauri
¶
-
class
webassets.filter.datauri.
CSSDataUri
(**kwargs)¶ Will replace CSS url() references to external files with internal data: URIs.
The external file is now included inside your CSS, which minimizes HTTP requests.
Note
Data Uris have clear disadvantages, so put some thought into if and how you would like to use them. Have a look at some performance measurements.
The filter respects a
DATAURI_MAX_SIZE
option, which is the maximum size (in bytes) of external files to include. The default limit is what I think should be a reasonably conservative number, 2048 bytes.
cssprefixer
¶
-
class
webassets.filter.cssprefixer.
CSSPrefixer
(**kwargs)¶ Uses CSSPrefixer to add vendor prefixes to CSS files.
autoprefixer
¶
-
class
webassets.filter.autoprefixer.
AutoprefixerFilter
(**kwargs)¶ Prefixes vendor-prefixes using autoprefixer <https://github.com/ai/autoprefixer>, which uses the Can I Use? <http://www.caniuse.com> database to know which prefixes need to be inserted.
This depends on the autoprefixer <https://github.com/ai/autoprefixer> command line tool being installed (use
npm install autoprefixer
).Supported configuration options:
- AUTOPREFIXER_BIN
- Path to the autoprefixer executable used to compile source files. By
default, the filter will attempt to run
autoprefixer
via the system path. - AUTOPREFIXER_BROWSERS
The browser expressions to use. This corresponds to the
--browsers <value>
flag, see the –browsers documentation <https://github.com/ai/autoprefixer#browsers>. By default, this flag won’t be passed, and autoprefixer’s default will be used.Example:
AUTOPREFIXER_BROWSERS = ['> 1%', 'last 2 versions', 'firefox 24', 'opera 12.1']
- AUTOPREFIXER_EXTRA_ARGS
- Additional options may be passed to
autoprefixer
using this setting, which expects a list of strings.
jinja2
¶
-
class
webassets.filter.jinja2.
Jinja2
(**kwargs)¶ Process a file through the Jinja2 templating engine.
Requires the
jinja2
package (https://github.com/mitsuhiko/jinja2).The Jinja2 context can be specified with the JINJA2_CONTEXT configuration option or directly with context={…}. Example:
Bundle('input.css', filters=Jinja2(context={'foo': 'bar'}))
Additionally to enable template loading mechanics from your project you can provide JINJA2_ENV or jinja2_env arg to make use of already created environment.
spritemapper
¶
-
class
webassets.filter.spritemapper.
Spritemapper
(**kwargs)¶ Generate CSS spritemaps using Spritemapper, a Python utility that merges multiple images into one and generates CSS positioning for the corresponding slices. Installation is easy:
pip install spritemapper
Supported configuration options:
- SPRITEMAPPER_PADDING
- A tuple of integers indicating the number of pixels of padding to place between sprites
- SPRITEMAPPER_ANNEAL_STEPS
- Affects the number of combinations to be attempted by the box packer algorithm
Note: Since the
spritemapper
command-line utility expects source and output files to be on the filesystem, this filter interfaces directly with library internals instead. It has been tested to work with Spritemapper version 1.0.