Skip to content

Instantly share code, notes, and snippets.

@Xowap
Last active February 10, 2018 22:51
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xowap/f01dad68418dbb8ab110 to your computer and use it in GitHub Desktop.
Save Xowap/f01dad68418dbb8ab110 to your computer and use it in GitHub Desktop.
Gulp Assets
# vim: fileencoding=utf-8 tw=100 expandtab ts=4 sw=4 :
from __future__ import unicode_literals
import json
import codecs
class AssetsLister(object):
def __init__(self, live, manifest):
self.manifest = manifest
self.live = live
self.cache = None
def find(self, bundle_name):
if self.live:
return self.find_live(bundle_name)
else:
return self.find_cached(bundle_name)
def find_live(self, bundle_name):
return self.load_file(self.manifest).get(bundle_name, [])
def find_cached(self, bundle_name):
if self.cache is None:
self.cache = self.load_file(self.manifest)
return self.cache.get(bundle_name, [])
def load_file(self, path):
with codecs.open(path, encoding='utf-8') as f:
return json.load(f)
# vim: fileencoding=utf-8 tw=100 expandtab ts=4 sw=4 :
from __future__ import unicode_literals
from django import template
from django.conf import settings
from django.template import Library
from ..gulp import AssetsLister
lister = AssetsLister(settings.DEBUG, settings.GULP_ASSET_MANIFEST)
register = Library()
class GulpAssetsNode(template.Node):
def __init__(self, bundle_name, child_nodes):
self.bundle_name = bundle_name
self.child_nodes = child_nodes
def render(self, context):
output = []
for file in lister.find(self.bundle_name):
context.update({
'asset_path': file,
})
try:
output.append(self.child_nodes.render(context))
finally:
context.pop()
return ''.join(output)
def gulp_assets(parser, token):
try:
tag_name, bundle_name = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
"%r tag requires a single argument" % token.contents.split()[0]
)
child_nodes = parser.parse(('endgulpassets',))
parser.delete_first_token()
if not (bundle_name[0] == bundle_name[-1] and bundle_name[0] in ('"', "'")):
raise template.TemplateSyntaxError(
"%r tag's argument should be in quotes" % tag_name
)
return GulpAssetsNode(bundle_name[1:-1], child_nodes)
register.tag('gulpassets', gulp_assets)
@Xowap
Copy link
Author

Xowap commented Jun 24, 2015

In HTML

    {% gulpassets "app" %}
        <script type="text/javascript" src="{% static asset_path %}"></script>
    {% endgulpassets %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment