Created
November 15, 2016 23:33
-
-
Save panayotoff/27d969afbb84e30a75b1677fc1026dd3 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
'use strict'; | |
window._ = {}; | |
_.templateSettings = { | |
evaluate: /<%([\s\S]+?)%>/g, | |
interpolate: /<%=([\s\S]+?)%>/g, | |
escape: /<%-([\s\S]+?)%>/g | |
}; | |
var escapes = { | |
"'": "'", | |
'\\': '\\', | |
'\r': 'r', | |
'\n': 'n', | |
'\u2028': 'u2028', | |
'\u2029': 'u2029' | |
}; | |
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; | |
var matcher = RegExp([ | |
(_.templateSettings.escape).source, | |
(_.templateSettings.interpolate).source, | |
(_.templateSettings.evaluate).source | |
].join('|') + '|$', 'g'); | |
var escapeChar = function (match) { | |
return '\\' + escapes[match]; | |
}; | |
_.template = function (text) { | |
var index = 0; | |
var source = "__p+='"; | |
text.replace(matcher, function (match, escape, interpolate, evaluate, offset) { | |
source += text.slice(index, offset).replace(escapeRegExp, escapeChar); | |
index = offset + match.length; | |
if (escape) { | |
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; | |
} | |
else if (interpolate) { | |
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; | |
} | |
else if (evaluate) { | |
source += "';\n" + evaluate + "\n__p+='"; | |
} | |
return match; | |
}); | |
source += "';\n"; | |
source = 'with(obj){\n' + source + '}\n'; | |
source = "var __t,__p='',__j=Array.prototype.join;\n" + | |
source + 'return __p;\n'; | |
var render = new Function('obj', '_', source); | |
var template = function (data) { | |
return render.call(this, data, _); | |
}; | |
return template; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment