From 0f8593f163dc354fcc6c1b1edee3e1984153a367 Mon Sep 17 00:00:00 2001 From: Alan Johnson Date: Thu, 16 Sep 2010 08:09:27 -0400 Subject: [PATCH] Got empty blocks working. --- lib/handlebars.js | 42 +++++++++++++++++++++++------------------- test/handlebars.js | 10 ++++++++++ 2 files changed, 33 insertions(+), 19 deletions(-) diff --git a/lib/handlebars.js b/lib/handlebars.js index 391e4088..4b8cf78a 100644 --- a/lib/handlebars.js +++ b/lib/handlebars.js @@ -172,6 +172,7 @@ var Handlebars = { out = out + lookup.call(context, arg, fn); } else if (typeof lookup != 'undefined') { + console.log(fn); out = out + Handlebars.helperMissing.call(arg, lookup, fn); } @@ -262,29 +263,32 @@ Handlebars.Compiler.prototype = { }, compile: function(endCondition) { - var chr; - while(chr = this.getChar()) { - if(chr === "{" && this.peek() === "{" && !this.mustache) { - this.getChar(); - this.parseMustache(); + // if we're at the end condition already then we don't have to do any work! + if (!endCondition || !endCondition(this)) { + var chr; + while(chr = this.getChar()) { + if(chr === "{" && this.peek() === "{" && !this.mustache) { + this.getChar(); + this.parseMustache(); - } else { - if(chr === "\n") { - this.newlines = this.newlines + "\n"; - chr = "\\n"; - } else if (chr === "\r") { - this.newlines = this.newlines + "\r"; - chr = "\\r"; + } else { + if(chr === "\n") { + this.newlines = this.newlines + "\n"; + chr = "\\n"; + } else if (chr === "\r") { + this.newlines = this.newlines + "\r"; + chr = "\\r"; + } + this.text = this.text + chr; } - this.text = this.text + chr; - } - if (endCondition && this.peek(5) == "{{^}}") { - this.continueInverted = true; - this.getChar(5); - break; + if (endCondition && this.peek(5) == "{{^}}") { + this.continueInverted = true; + this.getChar(5); + break; + } + else if(endCondition && endCondition(this)) { break }; } - else if(endCondition && endCondition(this)) { break }; } this.addText(); diff --git a/test/handlebars.js b/test/handlebars.js index 7b5744e0..9a8b6b93 100644 --- a/test/handlebars.js +++ b/test/handlebars.js @@ -138,6 +138,16 @@ test("array", function() { }); +test("empty block", function() { + var string = "{{#goodbyes}}{{/goodbyes}}cruel {{world}}!" + var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"}; + shouldCompileTo(string, hash, "cruel world!", + "Arrays iterate over the contents when not empty"); + + shouldCompileTo(string, {goodbyes: [], world: "world"}, "cruel world!", + "Arrays ignore the contents when empty"); +}); + test("nested iteration", function() { });