Skip to content

Instantly share code, notes, and snippets.

@mkoryak
Created December 10, 2013 21:53
Show Gist options
  • Save mkoryak/7900932 to your computer and use it in GitHub Desktop.
Save mkoryak/7900932 to your computer and use it in GitHub Desktop.
scripts jinjatag
import jinjatag
from bs4 import BeautifulSoup
import coffeescript
@jinjatag.simple_block()
def script(body, uglify=None):
if uglify is None:
uglify = not static.config.get('ASSETS_DEBUG', True)
soup = BeautifulSoup(body)
scripts = soup.findAll('script')
js = []
for script in scripts:
script_type = script.get('type', 'text/javascript').lower()
text = ''
if script_type == 'text/javascript':
text = script.get_text()
elif script_type == 'text/coffeescript':
text = coffeescript.compile(script.get_text())
js.append(text)
joined = ';\n'.join(js)
if uglify:
p = Popen(['uglifyjs', '--inline-script', '--lift-vars'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
else:
p = Popen(['uglifyjs', '-b', '--inline-script'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
output = p.communicate(input=joined)[0]
return "<script type='text/javascript'>{0}</script>".format(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment