Skip to content

Instantly share code, notes, and snippets.

@Fizzadar
Created July 15, 2014 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fizzadar/320ffb7e348fe62ae04c to your computer and use it in GitHub Desktop.
Save Fizzadar/320ffb7e348fe62ae04c to your computer and use it in GitHub Desktop.
Alternative to flask-webassets w/ autogenerated outfiles via simple jinja2 global
This is a page.
/* Some JS assets */
{{ assets(
'js/test.js', 'js/device.js',
filters='jsmin', extension='js') }}
/* Some CSS assets */
{{ assets(
'css/blah.css', 'css/print.css',
extension='css', rel='print') }}
# An alternative to flask-webassets which auto-generates out-file names based on the input files
# assumes that your flask.Application.static_url_path = '/inc'
# and that your flask.Application.static_path = 'static'
# and the webassets.Environment is created with args ('', '/inc')
from os import path
from itertools import chain
from hashlib import md5
from flask import Markup
from webassets import Bundle
# app = flask Application
# assets = webassets Environment
from app import app, assets
# Sadly webassets has no way to auto-generate outfile names
def bundle_assets(*files, **options):
extension = options.pop('extension', '')
filters = options.pop('filters', [])
# For css
rel = options.pop('rel', 'screen')
# Debug? just print out the file includes
if assets.debug:
files = ['/'.join(['inc', f]) for f in files]
if extension == 'js':
files = ['<script type="text/javascript" src="/{0}"></script>\n'.format(f) for f in files]
elif extension == 'css':
files = ['<link rel="stylesheet" rel="{0}" href="{1}" />\n'.format(rel, f) for f in files]
return Markup(''.join(files))
files = [
(f, 'static/{0}'.format(f))
for f in files
]
# Build a key based off the files in question
outfile = ''.join(chain.from_iterable((f[0], f[1]) for f in files))
outfile = md5(outfile).hexdigest()
bundle = None
# Does the bundle already exist?
if outfile not in assets:
bundle = Bundle(*[f[1] for f in files],
output='static/cache/{0}.{1}'.format(outfile, extension),
filters=filters
)
assets.register(outfile, bundle)
if extension == 'js':
outfile = '<script type="text/javascript" src="/inc/cache/{0}.{1}"></script>'.format(outfile, extension)
elif extension == 'css':
outfile = '<link rel="stylesheet" rel="{0}" href="{1}" />'.format(rel, extension)
return Markup(outfile)
app.jinja_env.globals['assets'] = bundle_assets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment