Skip to content

Instantly share code, notes, and snippets.

@wiky
Last active December 28, 2015 09:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wiky/7480740 to your computer and use it in GitHub Desktop.
Save wiky/7480740 to your computer and use it in GitHub Desktop.
(function() {
var cache = {};
this.tmpl = function(str, data) {
cache[str] = cache[str] ||
new Function('data', [
'var _p="";\nwith(arguments[0]||{}){\n_p+="',
str.replace(/"/g, '\\$&')
.replace(/[\r\n]/g, '')
.replace(/<%([^\w\s\}\)]*)\s*(.*?)\s*%>/g, function(match, mark, code) {
if (mark === '=') return '"+(' + code + ')+"';
if (mark === '') return '";\n' + code + '\n_p+="';
}),
'";\n}\nreturn _p;'].join(''));
return data ? cache[str](data) : cache[str];
};
})();
var tmpl = function(str, data) {
var source = str
.replace(/"/g, '\\$&')
.replace(/[\r\n]/g, '')
.replace(/<%([^\w\s\}\)]*)\s*(.*?)\s*%>/g, function(match, mark, code) {
if (mark === '=') {return '"+(' + code + ')+"';}
if (mark === '') {return '";\n' + code + '\n_p+="';}
});
source = 'var _p="";\nwith(data||{}){\n_p+="' + source + '";\n}\nreturn _p;';
var render = new Function('data', source);
return data ? render(data) : render;
};
// demo https://gist.github.com/wiky/6076971
// Performance Comparison with John Resig's micro-templating
// : http://jsperf.com/microtpl-vs-tpllite
// what's micro-templating? (http://ejohn.org/blog/javascript-micro-templating/)
@markyun
Copy link

markyun commented Nov 26, 2013

路过留名

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment