Attach template source to returned function.

This commit is contained in:
Brad Dunbar
2012-03-23 12:52:50 -04:00
parent ebb9db4e8e
commit 2055d745db

View File

@@ -938,28 +938,30 @@
// Underscore templating handles arbitrary delimiters, preserves whitespace, // Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code. // and correctly escapes quotes within interpolated code.
_.template = function(str, data) { _.template = function(str, data) {
var c = _.templateSettings; var settings = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + var source = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' + 'with(obj||{}){__p.push(\'' +
str str
.replace(escaper, function(match) { .replace(escaper, function(match) {
return '\\' + escapes[match]; return '\\' + escapes[match];
}) })
.replace(c.escape || noMatch, function(match, code) { .replace(settings.escape || noMatch, function(match, code) {
return "',_.escape(" + unescape(code) + "),\n'"; return "',\n_.escape(" + unescape(code) + "),\n'";
}) })
.replace(c.interpolate || noMatch, function(match, code) { .replace(settings.interpolate || noMatch, function(match, code) {
return "'," + unescape(code) + ",\n'"; return "',\n" + unescape(code) + ",\n'";
}) })
.replace(c.evaluate || noMatch, function(match, code) { .replace(settings.evaluate || noMatch, function(match, code) {
return "');" + unescape(code) + ";\n__p.push('"; return "');\n" + unescape(code) + "\n;__p.push('";
}) })
+ "');}return __p.join('');"; + "');\n}\nreturn __p.join('');";
var func = new Function('obj', '_', tmpl); var render = new Function('obj', '_', source);
if (data) return func(data, _); if (data) return render(data, _);
return function(data) { var template = function(data) {
return func.call(this, data, _); return render.call(this, data, _);
}; };
template.source = 'function(obj, _){\n' + source + '\n}';
return template;
}; };
// Add a "chain" function, which will delegate to the wrapper. // Add a "chain" function, which will delegate to the wrapper.