diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index b2ab3c6f..7d6c1ce2 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -86,7 +86,8 @@ Handlebars.registerHelper('each', function(context, fn, inverse) { }); Handlebars.registerHelper('if', function(context, fn, inverse) { - if(!context || context === []) { + var condition = typeof context === "function" ? context.call(this) : context; + if(!condition || condition == []) { return inverse(this); } else { return fn(this); diff --git a/spec/qunit_spec.js b/spec/qunit_spec.js index 39d4d64f..14531892 100644 --- a/spec/qunit_spec.js +++ b/spec/qunit_spec.js @@ -495,3 +495,27 @@ test("with", function() { shouldCompileTo(string, {person: {first: "Alan", last: "Johnson"}}, "Alan Johnson"); }); + +test("if with non-function argument", function() { + var string = "{{#if goodbye}}GOODBYE {{/if}}cruel {{world}}!"; + shouldCompileTo(string, {goodbye: true, world: "world"}, "GOODBYE cruel world!", + "if with boolean argument shows the contents when true"); + shouldCompileTo(string, {goodbye: "dummy", world: "world"}, "GOODBYE cruel world!", + "if with string argument shows the contents"); + shouldCompileTo(string, {goodbye: false, world: "world"}, "cruel world!", + "if with boolean argument does not show the contents when false"); + shouldCompileTo(string, {world: "world"}, "cruel world!", + "if with undefined does not show the contents"); +}); + +test("if with function argument", function() { + var string = "{{#if goodbye}}GOODBYE {{/if}}cruel {{world}}!"; + shouldCompileTo(string, {goodbye: function() {return true}, world: "world"}, "GOODBYE cruel world!", + "if with function shows the contents when function returns true"); + shouldCompileTo(string, {goodbye: function() {return this.world}, world: "world"}, "GOODBYE cruel world!", + "if with function shows the contents when function returns string"); + shouldCompileTo(string, {goodbye: function() {return false}, world: "world"}, "cruel world!", + "if with function does not show the contents when returns false"); + shouldCompileTo(string, {goodbye: function() {return this.foo}, world: "world"}, "cruel world!", + "if with function does not show the contents when returns undefined"); +});