Created
November 17, 2010 05:27
-
-
Save jleppert/703019 to your computer and use it in GitHub Desktop.
Simple jQuery Templating based on John Resig's Micro Templating
This file contains 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
(function($) { | |
var tpl_cache = {}; | |
var fn_cache = {}; | |
$.fn.tmpl = function(tpl, data, cb, fn, kd) { | |
var cb = typeof(cb) == 'function' ? cb : null; | |
var fn = fn || 'html'; | |
return this.each(function() { | |
doTpl(tpl, data, $(this), cb, fn, kd); | |
}); | |
} | |
var doTpl = function(tpl, data, el, cb, fn, kd) { | |
getTpl(tpl, function(tpl_data) { | |
fn_cache[tpl] = fn_cache[tpl] || | |
new Function("obj", | |
"var p=[],print=function(){p.push.apply(p,arguments);};" + | |
"with(obj){p.push('" + | |
tpl_data | |
.replace(/[\r\t\n]/g, " ") | |
.split("<%").join("\t") | |
.replace(/((^|%>)[^\t]*)'/g, "$1\r") | |
.replace(/\t=(.*?)%>/g, "',$1,'") | |
.split("\t").join("');") | |
.split("%>").join("p.push('") | |
.split("\r").join("\\'") | |
+ "');}return p.join('');"); | |
var r = $(fn_cache[tpl].call(this, data)); | |
if(kd) { | |
r.data(kd.key, kd.data); | |
} | |
el[fn](r); | |
if(cb) { | |
cb.call(el, data, r); | |
} | |
}); | |
} | |
var getTpl = function(tpl, cb) { | |
tpl_cache[tpl] ? cb.call(this, tpl_cache[tpl]) : | |
$.get(tpl, function(data) { | |
tpl_cache[tpl] = data; | |
cb.call(this, tpl_cache[tpl]); | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment