Skip to content

Instantly share code, notes, and snippets.

@HakurouKen
Created April 24, 2015 08:00
Show Gist options
  • Save HakurouKen/31a3332c9aa2c2b18457 to your computer and use it in GitHub Desktop.
Save HakurouKen/31a3332c9aa2c2b18457 to your computer and use it in GitHub Desktop.
A jQuery/Zepto template plugin based on MicroTemplate.
(function($) {
var cache = {};
var partial = function(str) {
return str.replace(/<%\+(.*)%>/, function(child, name) {
name = name.trim();
return !/[^\w-_]/.test(name) ? document.getElementById(name).innerHTML : name;
});
};
var tmpl = function tmpl(str, data) {
var fn = !/[^\w-_]/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
new Function("obj",
"var p=[]; with(obj){p.push('" +
partial(str)
.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('');");
return data ? fn(data) : fn;
};
$.extend({
tmpl: tmpl
});
$.fn.extend({
render: function(template, data) {
$(this).html($.tmpl(template, data));
}
});
})(jQuery || Zepto);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment