Skip to content

Commit

Permalink
Merge pull request jashkenas#560 from braddunbar/interpolate-null
Browse files Browse the repository at this point in the history
Fix jashkenas#556 - interpolate coerces null/undefined to ''.
  • Loading branch information
jashkenas committed Apr 18, 2012
2 parents bc8266d + b24be55 commit 67706cf
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
12 changes: 12 additions & 0 deletions test/utility.js
Expand Up @@ -192,4 +192,16 @@ $(document).ready(function() {
ok(!_.templateSettings.variable);
});

test('#556 - undefined template variables.', function() {
var template = _.template('<%=x%>');
strictEqual(template({x: null}), '');
strictEqual(template({x: undefined}), '');
});

test('interpolate evaluates code only once.', 1, function() {
var count = 0;
var template = _.template('<%= f() %>');
template({f: function(){ ok(!(count++)); }});
});

});
6 changes: 3 additions & 3 deletions underscore.js
Expand Up @@ -965,7 +965,7 @@
return "'+\n_.escape(" + unescape(code) + ")+\n'";
})
.replace(settings.interpolate || noMatch, function(match, code) {
return "'+\n(" + unescape(code) + ")+\n'";
return "'+\n((__t=(" + unescape(code) + "))==null?'':__t)+\n'";
})
.replace(settings.evaluate || noMatch, function(match, code) {
return "';\n" + unescape(code) + "\n;__p+='";
Expand All @@ -974,8 +974,8 @@
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

source = "var __p='';" +
"var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n" +
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'')};\n" +
source + "return __p;\n";

var render = new Function(settings.variable || 'obj', '_', source);
Expand Down

0 comments on commit 67706cf

Please sign in to comment.