Skip to content

@jboesch /simple_templating.js

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
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){
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
Something went wrong with that request. Please try again.