Skip to content

Instantly share code, notes, and snippets.

@Fizzadar

Fizzadar/mypage.html

Created Jul 15, 2014
Embed
What would you like to do?
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