Skip to content

Instantly share code, notes, and snippets.

@lwansbrough
Last active December 20, 2015 00:28
Show Gist options
  • Select an option

  • Save lwansbrough/6041546 to your computer and use it in GitHub Desktop.

Select an option

Save lwansbrough/6041546 to your computer and use it in GitHub Desktop.
"Un-templates" a DOM element which has been templated with a known *Mustache* template. Essentially, given the HTML content of a DOM element and the template used to create it, this function will return the object that was applied to the template.
var untemplate = (function() {
this.tokenize = function(html, template) {
var names = [],
obj = {},
encodedHtml = escape(html);
var templateRegex = new RegExp(escape(template).replace(/[\\\/\.\-\*]/g, function(match) {
return '\\' + match;
}).replace(/%7B%7B([^(?:%7B)]+?)%7D%7D/g, function(match, name) {
names.push(name);
return '(.*?)';
}), 'g');
encodedHtml.replace(templateRegex, function() {
for(var i = 1; i < arguments.length - 2; i++) {
obj[names[i - 1]] = unescape(arguments[i]);
}
});
return obj;
};
return this;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment