Skip to content

Commit

Permalink
Protect context-lookups from undefined values
Browse files Browse the repository at this point in the history
Fixes #166
Fixes #587
  • Loading branch information
kpdecker committed Nov 3, 2013
1 parent 88fefc1 commit ded0a16
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/handlebars/compiler/javascript-compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,25 @@ JavaScriptCompiler.prototype = {
// PUBLIC API: You can override these methods in a subclass to provide
// alternative compiled forms for name lookup and buffering semantics
nameLookup: function(parent, name /* , type*/) {
var wrap,
ret;
if (parent.indexOf('depth') === 0) {
wrap = true;
}

if (/^[0-9]+$/.test(name)) {
return parent + "[" + name + "]";
ret = parent + "[" + name + "]";
} else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
return parent + "." + name;
ret = parent + "." + name;
}
else {
return parent + "['" + name + "']";
ret = parent + "['" + name + "']";
}

if (wrap) {
return '(' + parent + ' && ' + ret + ')';
} else {
return ret;
}
},

Expand Down
6 changes: 6 additions & 0 deletions spec/basic.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ describe("basic context", function() {
"It works if all the required keys are provided");
});

it("compiling with an undefined context", function() {
shouldCompileTo("Goodbye\n{{cruel}}\n{{world.bar}}!", undefined, "Goodbye\n\n!");

shouldCompileTo("{{#unless foo}}Goodbye{{../test}}{{test2}}{{/unless}}", undefined, "Goodbye");
});

it("comments", function() {
shouldCompileTo("{{! Goodbye}}Goodbye\n{{cruel}}\n{{world}}!",
{cruel: "cruel", world: "world"}, "Goodbye\ncruel\nworld!",
Expand Down
7 changes: 7 additions & 0 deletions spec/partials.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ describe('partials', function() {
"Partials can be passed a context");
});

it("partials with undefined context", function() {
var string = "Dudes: {{>dude dudes}}";
var partial = "{{foo}} Empty";
var hash = {};
shouldCompileToWithPartials(string, [hash, {}, {dude: partial}], true, "Dudes: Empty");
});

it("partial in a partial", function() {
var string = "Dudes: {{#dudes}}{{>dude}}{{/dudes}}";
var dude = "{{name}} {{> url}} ";
Expand Down

0 comments on commit ded0a16

Please sign in to comment.