Make helperMissing a built-in feature

This commit is contained in:
wycats
2010-12-11 18:28:37 -08:00
parent 5097c18912
commit 215754c268
2 changed files with 31 additions and 26 deletions
+24 -3
View File
@@ -29,11 +29,11 @@ Handlebars.compile = function(string) {
var helpers, partials; var helpers, partials;
if(!helpers) { if(!helpers) {
helpers = this.helpers; helpers = Handlebars.helpers;
} }
if(!partials) { if(!partials) {
partials = this.partials; partials = Handlebars.partials;
} }
var runtime = new Handlebars.Runtime(context, helpers, partials); var runtime = new Handlebars.Runtime(context, helpers, partials);
@@ -45,13 +45,34 @@ Handlebars.compile = function(string) {
Handlebars.helpers = {}; Handlebars.helpers = {};
Handlebars.partials = {}; Handlebars.partials = {};
Handlebars.registerHelper = function(name, fn) { Handlebars.registerHelper = function(name, fn, inverse) {
if(inverse) { fn.not = inverse; }
this.helpers[name] = fn; this.helpers[name] = fn;
}; };
Handlebars.registerPartial = function(name, str) { Handlebars.registerPartial = function(name, str) {
this.partials[name] = str; this.partials[name] = str;
}; };
Handlebars.registerHelper('helperMissing', function(context, fn) {
var ret = "";
if(context === true) {
return fn(this);
} else if(context === false) {
return "";
} else if(Object.prototype.toString.call(context) === "[object Array]") {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn(context[i]);
}
return ret;
} else {
return fn(context);
}
}, function(context, fn) {
return fn(context)
});
// END(BROWSER) // END(BROWSER)
exports.Handlebars = Handlebars; exports.Handlebars = Handlebars;
+7 -23
View File
@@ -1,33 +1,17 @@
module("basic context"); module("basic context");
var helperMissing = function(context, fn) {
var ret = "";
if(context === true) {
return fn(this);
} else if(context === false) {
return "";
} else if(Object.prototype.toString.call(context) === "[object Array]") {
for(var i=0, j=context.length; i<j; i++) {
ret = ret + fn(context[i]);
}
return ret;
} else {
return fn(context);
}
};
helperMissing.not = function(context, fn) {
return fn(context);
}
var shouldCompileTo = function(string, hash, expected, message) { var shouldCompileTo = function(string, hash, expected, message) {
var template = Handlebars.compile(string); var template = Handlebars.compile(string);
if(Object.prototype.toString.call(hash) === "[object Array]") { if(Object.prototype.toString.call(hash) === "[object Array]") {
hash[1].helperMissing = helperMissing; if(hash[1]) {
for(var prop in Handlebars.helpers) {
hash[1][prop] = Handlebars.helpers[prop];
}
}
} else { } else {
hash = [hash, {helperMissing: helperMissing}]; hash = [hash];
} }
result = template.apply(this, hash) result = template.apply(this, hash)
equal(result, expected, "'" + expected + "' should === '" + result + "': " + message); equal(result, expected, "'" + expected + "' should === '" + result + "': " + message);
} }