public
Last active

  • Download Gist
simple_templating.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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;
});
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.