Skip to content

Commit

Permalink
Add includeZero flag to if conditional
Browse files Browse the repository at this point in the history
Allows for users who desire non-falsy handling of numbers to utilize if while maintaining the legacy if behavior.

Fixes #608
  • Loading branch information
kpdecker committed Oct 15, 2013
1 parent 2cd0995 commit 84049bf
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
7 changes: 5 additions & 2 deletions lib/handlebars/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,18 @@ 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);
}
});

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) {
Expand Down
7 changes: 5 additions & 2 deletions spec/builtins.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down

0 comments on commit 84049bf

Please sign in to comment.