From ded0a1617fda248252a92d71b12c62a5e8536c33 Mon Sep 17 00:00:00 2001 From: kpdecker Date: Sun, 3 Nov 2013 10:54:24 -0600 Subject: [PATCH] Protect context-lookups from undefined values Fixes #166 Fixes #587 --- lib/handlebars/compiler/javascript-compiler.js | 18 +++++++++++++++--- spec/basic.js | 6 ++++++ spec/partials.js | 7 +++++++ 3 files changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/handlebars/compiler/javascript-compiler.js b/lib/handlebars/compiler/javascript-compiler.js index b04ef1ad3..57af1d449 100644 --- a/lib/handlebars/compiler/javascript-compiler.js +++ b/lib/handlebars/compiler/javascript-compiler.js @@ -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; } }, diff --git a/spec/basic.js b/spec/basic.js index 4ee65efdf..ee154a165 100644 --- a/spec/basic.js +++ b/spec/basic.js @@ -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!", diff --git a/spec/partials.js b/spec/partials.js index fa2fa56d4..7ff9d3c25 100644 --- a/spec/partials.js +++ b/spec/partials.js @@ -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}} ";