From b2b5a5390bed8682cb78562deb42d69c8170978f Mon Sep 17 00:00:00 2001 From: Jeremy Ashkenas Date: Tue, 20 Jul 2010 13:37:27 -0400 Subject: [PATCH] merging a variant of svieira's fix for preserving whitespace within templates. --- test/utility.js | 3 +++ underscore.js | 10 ++++++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/test/utility.js b/test/utility.js index 7673eadfa..8670a9fda 100644 --- a/test/utility.js +++ b/test/utility.js @@ -69,6 +69,9 @@ $(document).ready(function() { var quoteInStatementAndBody = _.template("<% if(foo == 'bar'){ %>Statement quotes and 'quotes'.<% } %>"); equals(quoteInStatementAndBody({foo: "bar"}), "Statement quotes and 'quotes'."); + var withNewlinesAndTabs = _.template('This\n\t\tis: <%= x %>.\n\tok.\nend.'); + equals(withNewlinesAndTabs({x: 'that'}), 'This\n\t\tis: that.\n\tok.\nend.'); + _.templateSettings = { start : '{{', end : '}}', diff --git a/underscore.js b/underscore.js index 5d45d8536..ded7d9b14 100644 --- a/underscore.js +++ b/underscore.js @@ -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('")