Allow function parameters to #if. This was originally disallowed because it is decidedly not idiomatic Handlebars, which would prefer that you use helpers for these cases, not pollute your context objects with functions to call from your template, but enough people asked for it that I'll give in.

I will personally not be using this feature and still strongly recommend that people use helpers in this case.
This commit is contained in:
Yehuda Katz
2011-12-27 15:47:45 -08:00
parent 9852502636
commit 69307d0e2b
2 changed files with 19 additions and 4 deletions
+7 -4
View File
@@ -23,16 +23,16 @@ Handlebars.registerHelper('helperMissing', function(arg) {
}
});
var toString = Object.prototype.toString, functionType = "[object Function]";
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
var inverse = options.inverse || function() {}, fn = options.fn;
var ret = "";
var type = Object.prototype.toString.call(context);
var type = toString.call(context);
if(type === "[object Function]") {
context = context();
}
if(type === functionType) { context = context.call(this); }
if(context === true) {
return fn(this);
@@ -67,6 +67,9 @@ Handlebars.registerHelper('each', function(context, options) {
});
Handlebars.registerHelper('if', function(context, options) {
var type = toString.call(context);
if(type === functionType) { context = context.call(this); }
if(!context || Handlebars.Utils.isEmpty(context)) {
return options.inverse(this);
} else {
+12
View File
@@ -598,6 +598,18 @@ test("if", function() {
"if with empty array 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");
});
test("each", function() {
var string = "{{#each goodbyes}}{{text}}! {{/each}}cruel {{world}}!"
var hash = {goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}], world: "world"};