Skip to content

Commit

Permalink
merging a variant of svieira's fix for preserving whitespace within t…
Browse files Browse the repository at this point in the history
…emplates.
  • Loading branch information
jashkenas committed Jul 20, 2010
1 parent ef396a9 commit b2b5a53
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
3 changes: 3 additions & 0 deletions test/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 : '}}',
Expand Down
10 changes: 6 additions & 4 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -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('")
Expand Down

0 comments on commit b2b5a53

Please sign in to comment.