From 84049bf0c5576727e9d6a0880abb123454d28861 Mon Sep 17 00:00:00 2001 From: kpdecker Date: Mon, 14 Oct 2013 21:36:46 -0500 Subject: [PATCH] Add includeZero flag to if conditional Allows for users who desire non-falsy handling of numbers to utilize if while maintaining the legacy if behavior. Fixes #608 --- lib/handlebars/base.js | 7 +++++-- spec/builtins.js | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index a1b346104..dcf446b78 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -133,7 +133,10 @@ function registerDefaultHelpers(instance) { instance.registerHelper('if', function(conditional, options) { if (isFunction(conditional)) { conditional = conditional.call(this); } - if (Utils.isEmpty(conditional)) { + // Default behavior is to render the positive path if the value is truthy and not empty. + // The `includeZero` option may be set to treat the condtional as purely not empty based on the + // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. + if ((!options.hash.includeZero && !conditional) || Utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); @@ -141,7 +144,7 @@ function registerDefaultHelpers(instance) { }); instance.registerHelper('unless', function(conditional, options) { - return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn}); + return instance.helpers['if'].call(this, conditional, {fn: options.inverse, inverse: options.fn, hash: options.hash}); }); instance.registerHelper('with', function(context, options) { diff --git a/spec/builtins.js b/spec/builtins.js index 140f5f510..401e789a9 100644 --- a/spec/builtins.js +++ b/spec/builtins.js @@ -15,8 +15,11 @@ describe('builtin helpers', function() { "if with non-empty array shows the contents"); shouldCompileTo(string, {goodbye: [], world: "world"}, "cruel world!", "if with empty array does not show the contents"); - shouldCompileTo(string, {goodbye: 0, world: "world"}, "GOODBYE cruel world!", - "if with zero does show the contents"); + shouldCompileTo(string, {goodbye: 0, world: "world"}, "cruel world!", + "if with zero does not show the contents"); + shouldCompileTo("{{#if goodbye includeZero=true}}GOODBYE {{/if}}cruel {{world}}!", + {goodbye: 0, world: "world"}, "GOODBYE cruel world!", + "if with zero does not show the contents"); }); it("if with function argument", function() {