Created
August 12, 2015 14:12
-
-
Save allenhwkim/caa7e72f8f6665057b69 to your computer and use it in GitHub Desktop.
micro template
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
'use strict'; | |
var _cache = {}; | |
var microTemplate = function(str, data) { | |
var func = _cache[str]; | |
if (!func) { | |
var strFunc = | |
"var p=[],print=function(){p.push.apply(p,arguments);};" + | |
"with(obj){p.push('" + | |
//str.replace(/[\r\t\n]/g, " ") | |
str.replace(/[\r]/g, "::BR::") //replace white spaces to special ones | |
.replace(/[\n]/g, "::BN::") | |
.replace(/[\t]/g, "::BT::") | |
.replace(/'(?=[^%]*%>)/g, "\t") | |
.split("'").join("\\'") | |
.split("\t").join("'") | |
.replace(/<%=(.+?)%>/g, "',$1,'") | |
.split("<%").join("');") | |
.split("%>").join("p.push('") + "');}return p.join('');"; | |
func = new Function("obj", strFunc); | |
_cache[str] = func; | |
} | |
var output = func(data) | |
.replace(/::BR::/g, "\r") // recover white spaces | |
.replace(/::BN::/g, "\n") | |
.replace(/::BT::/g, "\t"); | |
return output; | |
}; | |
module.exports = microTemplate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment