Created
February 8, 2013 23:54
-
-
Save adatta02/4742965 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
_.template = function(text, data, settings) { | |
settings = _.defaults(settings || {}, _.templateSettings); | |
// Compile the template source, taking care to escape characters that | |
// cannot be included in a string literal and then unescape them in code | |
// blocks. | |
var source = "__p+='" + text | |
.replace(escaper, function(match) { | |
return '\\' + escapes[match]; | |
}) | |
.replace(settings.escape || noMatch, function(match, code) { | |
return "'+\n_.escape(" + unescape(code) + ")+\n'"; | |
}) | |
.replace(settings.interpolate || noMatch, function(match, code) { | |
return "'+\n(" + unescape(code) + ")+\n'"; | |
}) | |
.replace(settings.evaluate || noMatch, function(match, code) { | |
return "';\n" + unescape(code) + "\n;__p+='"; | |
}) + "';\n"; | |
// If a variable is not specified, place data values in local scope. | |
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; | |
source = "var __p='';" + | |
"var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" + | |
source + "return __p;\n"; | |
var render = new Function(settings.variable || 'obj', '_', source); | |
if (data) return render(data, _); | |
var template = function(data) { | |
return render.call(this, data, _); | |
}; | |
// Provide the compiled function source as a convenience for build time | |
// precompilation. | |
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + | |
source + '}'; | |
return template; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment