Tweaked block helpers to wrap 'this' up in a context helper correctly.
This commit is contained in:
+1
-1
@@ -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 = "<ul>{{#people}}<li>{{#link}}{{name}}{{/link}}</li>{{/people}}</ul>";
|
||||
var link = function(fn) {
|
||||
var link = function(context, fn) {
|
||||
return '<a href="/people/' + this.__get__("id") + '">' + fn(this) + '</a>';
|
||||
};
|
||||
var template = Handlebars.compile(source);
|
||||
|
||||
+3
-2
@@ -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 += "}";
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,19 @@ test("block helper staying in the same context", function() {
|
||||
equal(result, "<form><p>Yehuda</p></form>");
|
||||
});
|
||||
|
||||
test("block helper should have wrapped context in this", function() {
|
||||
var source = "<ul>{{#people}}<li>{{#link}}{{name}}{{/link}}</li>{{/people}}</ul>";
|
||||
var link = function(context, fn) {
|
||||
return '<a href="/people/' + this.__get__("id") + '">' + fn(this) + '</a>';
|
||||
};
|
||||
var data = { "people": [
|
||||
{ "name": "Alan", "id": 1 },
|
||||
{ "name": "Yehuda", "id": 2 }
|
||||
]};
|
||||
|
||||
shouldCompileTo(source, [data, {link: link}], "<ul><li><a href=\"/people/1\">Alan</a></li><li><a href=\"/people/2\">Yehuda</a></li></ul>");
|
||||
});
|
||||
|
||||
test("block helper passing a new context", function() {
|
||||
var string = "{{#form yehuda}}<p>{{name}}</p>{{/form}}"
|
||||
var template = Handlebars.compile(string);
|
||||
|
||||
Reference in New Issue
Block a user