Added basic nested context lookups and context stack.

This commit is contained in:
Alan Johnson
2010-08-02 23:29:37 -04:00
parent ae98f233f1
commit acfef657d4
2 changed files with 23 additions and 2 deletions
+16 -2
View File
@@ -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;
+7
View File
@@ -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);