Created
March 31, 2010 04:24
-
-
Save jboesch/349932 to your computer and use it in GitHub Desktop.
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 Template = { | |
// Keep track of used selector text to prevent re-quering the DOM | |
_cache: {}, | |
/** | |
* If you've already called this.draw() on a certain template and don't want to lose your data, you | |
* can append some more data by calling append() | |
* @param {String} tpl The template string that you created with draw(); | |
* @param {Object} data The data you're passing | |
*/ | |
append: function(tpl, data){ | |
return this._replacement(tpl, data); | |
}, | |
/** | |
* Grab the template in the HTML based on the selector and parse it | |
* @param {String} selector The jQuery selector to use to grab the HTML | |
* @param {Object} data The data you're passing | |
*/ | |
draw: function(selector, data){ | |
if(!this._cache[selector]){ | |
this._cache[selector] = (typeof(jQuery) !== 'undefined') ? jQuery(selector).html() : document.getElementById(selector).text; | |
} | |
return this._replacement(this._cache[selector], data); | |
}, | |
/** | |
* This is what's happening behind the scenes, regex replace the data and pass it back | |
* @param {String} t The template string | |
* @param {Object} data The data you're passing | |
*/ | |
_replacement: function(t, data){ | |
return t.replace(/<%=?(.*?)%>/g, function (matched, group) { | |
// Same as calling String.prototype.trim() | |
var g = group.replace(/^\s+|\s+$/g, ""); | |
// Only disallow undefined values | |
return (data && typeof(data[g]) !== 'undefined') ? data[g] : matched; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment