Last active
December 20, 2015 00:28
-
-
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.
This file contains hidden or 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 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