Added basic nested context lookups and context stack.
This commit is contained in:
+16
-2
@@ -2,7 +2,7 @@ Handlebars = {
|
||||
compile: function(string) {
|
||||
var compiler = new Handlebars.Compiler(string);
|
||||
var result = compiler.compile();
|
||||
return new Function("context", "fallback", "fallback = fallback || {}; " + result);
|
||||
return new Function("context", "fallback", "fallback = fallback || {}; stack = [];" + result);
|
||||
},
|
||||
|
||||
isFunction: function(fn) {
|
||||
@@ -84,7 +84,19 @@ Handlebars.Compiler.prototype = {
|
||||
},
|
||||
|
||||
lookupFor: function(param) {
|
||||
return param ? "( context['" + param + "'] || fallback['" + param + "'] )" : "context";
|
||||
if (!param) {
|
||||
return "context";
|
||||
}
|
||||
|
||||
var parts = param.split("../");
|
||||
param = parts[parts.length - 1];
|
||||
depth = parts.length - 1;
|
||||
|
||||
if (depth > 0) {
|
||||
return "( stack[stack.length - " + depth + "]['" + param + "'] )";
|
||||
} else {
|
||||
return "( context['" + param + "'] || fallback['" + param + "'] )";
|
||||
}
|
||||
},
|
||||
|
||||
parseMustache: function() {
|
||||
@@ -133,9 +145,11 @@ Handlebars.Compiler.prototype = {
|
||||
var fnId = "fn" + this.pointer.toString();
|
||||
|
||||
this.fn += "var " + fnId + " = function(context) {" + result + "}; ";
|
||||
this.fn += "stack.push(context);"
|
||||
this.fn += "lookup = " + this.lookupFor(mustache) + "; ";
|
||||
this.fn += "if(Handlebars.isFunction(lookup)) out = out + lookup.call(" + param + ", " + fnId + "); "
|
||||
this.fn += "else if(typeof lookup !== 'undefined') out = out + Handlebars.helperMissing.call(" + param + ", lookup, " + fnId + "); "
|
||||
this.fn += "stack.pop(context);"
|
||||
|
||||
this.openBlock = false;
|
||||
return;
|
||||
|
||||
@@ -42,6 +42,13 @@ test("nested iteration", function() {
|
||||
|
||||
});
|
||||
|
||||
test("block with complex lookup", function() {
|
||||
var string = "{{#goodbyes}}{{text}} cruel {{../name}}! {{/goodbyes}}"
|
||||
var hash = {name: "Alan", goodbyes: [{text: "goodbye"}, {text: "Goodbye"}, {text: "GOODBYE"}]};
|
||||
|
||||
shouldCompileTo(string, hash, "goodbye cruel Alan! Goodbye cruel Alan! GOODBYE cruel Alan! ");
|
||||
});
|
||||
|
||||
test("block helper", function() {
|
||||
var string = "{{#goodbyes}}{{text}}! {{/goodbyes}}cruel {{world}}!";
|
||||
var template = Handlebars.compile(string);
|
||||
|
||||
Reference in New Issue
Block a user