Fixing Issue #35. newlines in evaluated code.

This commit is contained in:
Jeremy Ashkenas
2010-09-27 17:35:43 -04:00
parent 902f1192e0
commit fbd682d9ec
3 changed files with 22 additions and 26 deletions

View File

@@ -617,8 +617,7 @@
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
start : '<%',
end : '%>',
evaluate : /<%(.+?)%>/g,
interpolate : /<%=(.+?)%>/g
};
@@ -628,21 +627,22 @@
// With alterations for arbitrary delimiters, and to preserve whitespace.
_.template = function(str, data) {
var c = _.templateSettings;
var endMatch = new RegExp("'(?=[^"+c.end.substr(0, 1)+"]*"+escapeRegExp(c.end)+")","g");
var fn = new Function('obj',
'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\r/g, '\\r')
str.split("'").join("\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(endMatch,"✄")
.split("'").join("\\'")
.split("✄").join("'")
.replace(c.interpolate, "',$1,'")
.split(c.start).join("');")
.split(c.end).join("__p.push('")
+ "');}return __p.join('');");
return data ? fn(data) : fn;
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
// ------------------------------- Aliases ----------------------------------