merging a variant of svieira's fix for preserving whitespace within templates.

This commit is contained in:
Jeremy Ashkenas
2010-07-20 13:37:27 -04:00
parent ef396a9e13
commit b2b5a5390b
2 changed files with 9 additions and 4 deletions

View File

@@ -625,17 +625,19 @@
// JavaScript templating a-la ERB, pilfered from John Resig's
// "Secrets of the JavaScript Ninja", page 83.
// Single-quote fix from Rick Strahl's version.
// With alterations for arbitrary delimiters.
// 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);};' +
'with(obj||{}){p.push(\'' +
str.replace(/[\r\t\n]/g, " ")
.replace(endMatch,"\t")
str.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(endMatch,"✄")
.split("'").join("\\'")
.split("\t").join("'")
.split("").join("'")
.replace(c.interpolate, "',$1,'")
.split(c.start).join("');")
.split(c.end).join("p.push('")