Created
December 4, 2015 17:04
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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