Created
April 24, 2015 08:00
-
-
Save HakurouKen/31a3332c9aa2c2b18457 to your computer and use it in GitHub Desktop.
A jQuery/Zepto template plugin based on MicroTemplate.
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 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