This can be achieved by adding the following add_javascript and
get_javascripts functions to template globals.
combined_javascripts = {}
def add_javascript(path):
web.ctx.setdefault('javascripts', []).append(path)
def get_javascripts():
# combine javascripts only in the production environment
if web.config.debug:
return web.ctx.javascripts
else:
key = tuple(web.ctx.javascripts)
if key not in combined_javascripts:
filename = combine(web.ctx.javascripts)
combined_style[key] = [filename]
return combined_javascripts[key]
def combine(paths):
data = "\n".join([open(path).read() for path in paths])
# use md5 to generate unique filename
filename = "all_" + md5.md5.digest(data).hexdigest() + ".js"
f = open(filename, 'w')
f.write(data)
f.close()
return filename
The templates can call $add_javascript when it want to add javascript
files to the template and the base template should have get all the
added javascripts by calling get_javascripts.
$add_javascript("/static/jquery.js")
$add_javascript("/static/jquery.ui.js")
$for js in get_javascripts():
<script src="$js" type="text/javascript"/>