Last active
December 28, 2015 09:39
-
-
Save wiky/7480740 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 = {}; | |
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]; | |
}; | |
})(); |
This file contains hidden or 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
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/) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
路过留名