Skip to content

Instantly share code, notes, and snippets.

@danizen
Created March 9, 2020 20:15
Show Gist options
  • Save danizen/8d41f63c7bb4e35793a8e5d4d41fac16 to your computer and use it in GitHub Desktop.
Save danizen/8d41f63c7bb4e35793a8e5d4d41fac16 to your computer and use it in GitHub Desktop.
Django app to load from a webapp bundle
import os
import re
import logging
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from django.templatetags.static import static
from loader.utils import BundleMap
logger = logging.getLogger(__name__)
if not settings.DEBUG:
_map = BundleMap(settings.STATIC_ROOT)
register = template.Library()
@register.simple_tag
def load_cssbundle(name):
if settings.DEBUG:
fname = '{}.bundle.css'.format(name)
else:
fname = _map.get_bundle('css', name)
logger.debug('Serving css bundle {} from {}'.format(name, fname))
return mark_safe('<link rel="stylesheet" href="{}"/>'.format(static(fname)))
@register.simple_tag
def load_jsbundle(name):
if settings.DEBUG:
fname = '{}.bundle.js'.format(name)
else:
fname = _map.get_bundle('js', name)
logger.debug('Serving js bundle {} from {}'.format(name, fname))
return mark_safe('<script src="{}"></script>'.format(static(fname)))
import os
import re
class BundleMap(object):
def __init__(self, rootpath):
self.rootpath = rootpath
self.rebuild()
def rebuild(self):
self.map = { 'css': {}, 'js': {} }
for name in os.listdir(self.rootpath):
m = re.match(r'([a-z]+)\.[a-z0-9]+\.bundle.(js|css)', name)
if m is not None:
bname = m.group(1)
btype = m.group(2)
if btype in self.map:
self.map[btype][bname] = name
def get_bundle(self, btype, name):
return self.map[btype][name] if name in self.map[btype] else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment