diff --git a/README.markdown b/README.markdown
index b6e4fea5..bafd2010 100644
--- a/README.markdown
+++ b/README.markdown
@@ -58,7 +58,7 @@ would render:
Handlebars.js also adds the ability to define block helpers. Block helpers are functions that can be called from anywhere in the template. Here's an example:
var source = "
{{#people}}- {{#link}}{{name}}{{/link}}
{{/people}}
";
- var link = function(fn) {
+ var link = function(context, fn) {
return '' + fn(this) + '';
};
var template = Handlebars.compile(source);
diff --git a/lib/handlebars.js b/lib/handlebars.js
index aaba40da..3d651154 100644
--- a/lib/handlebars.js
+++ b/lib/handlebars.js
@@ -324,16 +324,17 @@ Handlebars.Compiler.prototype = {
// don't need to be globally unique, just per compiler
var fnId = "fn" + this.pointer.toString();
this.fn += "var proxy = Handlebars.buildContext(" + param + ", stack);";
+ this.fn += "var wrappedContext = Handlebars.buildContext(context);";
this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
- this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(context, proxy, " + fnId + "); ";
+ this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(wrappedContext, proxy, " + fnId + "); ";
this.fn += "else if(typeof lookup !== 'undefined') { out = out + Handlebars.helperMissing.call(proxy, lookup, " + fnId + "); }";
if (compiler.continueInverted) {
var invertedCompiler = this.compileToEndOfBlock(mustache);
this.fn += "if (Handlebars.isFunction(lookup.not)) {";
this.fn += " var " + fnId + "Not = function(context) { " + invertedCompiler.fn + " };";
- this.fn += " out = out + lookup.not.call(context, proxy, " + fnId + "Not);";
+ this.fn += " out = out + lookup.not.call(wrappedContext, proxy, " + fnId + "Not);";
this.fn += "}";
}
diff --git a/test/handlebars.js b/test/handlebars.js
index e090ac32..649830f0 100644
--- a/test/handlebars.js
+++ b/test/handlebars.js
@@ -177,6 +177,19 @@ test("block helper staying in the same context", function() {
equal(result, "");
});
+test("block helper should have wrapped context in this", function() {
+ var source = "{{#people}}- {{#link}}{{name}}{{/link}}
{{/people}}
";
+ var link = function(context, fn) {
+ return '' + fn(this) + '';
+ };
+ var data = { "people": [
+ { "name": "Alan", "id": 1 },
+ { "name": "Yehuda", "id": 2 }
+ ]};
+
+ shouldCompileTo(source, [data, {link: link}], "");
+});
+
test("block helper passing a new context", function() {
var string = "{{#form yehuda}}{{name}}
{{/form}}"
var template = Handlebars.compile(string);