Skip to content

Instantly share code, notes, and snippets.

@mleavitt
Created April 6, 2013 19:45
Show Gist options
  • Save mleavitt/5327358 to your computer and use it in GitHub Desktop.
Save mleavitt/5327358 to your computer and use it in GitHub Desktop.
Sample "wrapAMD" function for finding the partials dependencies in a compiled Handlebars template function and wrapping it in an AMD definition function with the partials inserted into the dependencies array.
wrapAMD: function (output) {
var dependencies = ['handlebars'];
for ( var i = 0; i < output.length; i++ ) {
// find partials defined as partials['partial-name']
var template = output[i]
, partialStart = 'partials\\[\''
, partialEnd = '\\\']'
, partialsRegex = new RegExp( partialStart + '[^\n]*' + partialEnd, 'g')
, dependency = template.match(partialsRegex)
, l = dependency ? dependency.length-1 : -1;
// isolate the partial name and add it to the dependencies array
while( l > -1 ) {
dependencies.push(dependency[l].replace(new RegExp(partialStart), '').replace(new RegExp(partialEnd), '').replace(/\s/g, ''));
l--;
}
// find partials defined as partials.partialName
partialStart = 'partials\\.';
partialEnd = ',';
partialsRegex = /partials\.[^\s]*/g;
dependency = template.match(partialsRegex);
l = dependency ? dependency.length-1 : -1;
// isolate the partial name and add it to the dependencies array
while( l > -1 ) {
dependencies.push(dependency[l].replace(new RegExp(partialStart), '').replace(new RegExp(partialEnd), '').replace(/\s/g, ''));
l--;
}
}
// remove redundant dependencies
dependencies = _.uniq(dependencies)
output.unshift("define(['" + dependencies.join("','") + "'], function(Handlebars) {");
output.push("});");
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment