Skip to content

Instantly share code, notes, and snippets.

@amy-langley
Created December 4, 2015 17:04
Show Gist options
  • Save amy-langley/b102bb356a93178eb441 to your computer and use it in GitHub Desktop.
Save amy-langley/b102bb356a93178eb441 to your computer and use it in GitHub Desktop.
TFW you throw together an HTML template compiler b/c you can't use a decent framework
var compile = function(selector){
var r = /(\{\{.+?\}\})/;
var elem = document.querySelector(selector);
var markup = elem.outerHTML;
elem.remove();
markup = markup.replace(/\s+/,' ');
var fragments = markup.split(r);
var template = (function(tpl){
return function(obj){
var r = /(\{\{.+?\}\})/;
var accum = [];
for(var idx in fragments){
var fragment = fragments[idx];
if(r.test(fragment)){
fragment = fragment.replace(/(\{\{)|(\}\})/g,'');
accum.push(obj[fragment]);
} else {
accum.push(fragment);
}
}
return accum.join('');
};
})(fragments);
return template;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment