diff --git a/lib/compiler.js b/lib/compiler.js index 92774d6..9e1ea5d 100644 --- a/lib/compiler.js +++ b/lib/compiler.js @@ -252,7 +252,7 @@ function stringifySubstitutions(obj) { var items = []; for (var key in obj) { - items.push('"' + esc(key) + '": function(c,p,t,i) {' + obj[key] + '}'); + items.push('"' + esc(key) + '": { f: function(c,p,t,i) {' + obj[key].code + '}, lvl:' + obj[key].lvl + ' }'); } return "{ " + items.join(",") + " }"; } @@ -270,8 +270,10 @@ } var serialNo = 0; + var lvl = 0; Hogan.generate = function(tree, text, options) { serialNo = 0; + lvl = 0; var context = { code: '', subs: {}, partials: {} }; Hogan.walk(tree, context); @@ -299,8 +301,10 @@ for (key in template.partials) { template.partials[key] = this.makePartials(template.partials[key]); } + var sub; for (key in codeObj.subs) { - template.subs[key] = new Function('c', 'p', 't', 'i', codeObj.subs[key]); + sub = codeObj.subs[key]; + template.subs[key] = { f: new Function('c', 'p', 't', 'i', sub.code), lvl:sub.lvl }; } return template; } @@ -352,8 +356,9 @@ '$': function(node, context) { var ctx = {subs: {}, code: '', partials: context.partials, prefix: node.n}; + lvl++; Hogan.walk(node.nodes, ctx); - context.subs[node.n] = ctx.code; + context.subs[node.n] = { code: ctx.code, lvl: lvl-- }; if (!context.inPartial) { context.code += 't.sub("' + esc(node.n) + '",c,p,i);'; } diff --git a/lib/template.js b/lib/template.js index 14f396d..d38cbb5 100644 --- a/lib/template.js +++ b/lib/template.js @@ -250,7 +250,8 @@ var Hogan = {}; }, sub: function(name, context, partials, indent) { - var f = this.subs[name]; + var sub = (this.subs[name]?this.subs[name]:undefined); + var f = (sub?sub.f:undefined); if (f) { this.activeSub = name; f(context, partials, this, indent); @@ -293,10 +294,10 @@ var Hogan = {}; partial.stackSubs = stackSubs; partial.subsText = stackText; for (key in subs) { - if (!stackSubs[key]) stackSubs[key] = subs[key]; + if (!stackSubs[key] || stackSubs[key].lvl < subs[key].lvl) stackSubs[key] = subs[key]; } for (key in stackSubs) { - partial.subs[key] = stackSubs[key]; + partial.subs[key] = (subs[key] && subs[key].lvl > stackSubs[key].lvl)?subs[key]:stackSubs[key]; } stackPartials = stackPartials || {}; diff --git a/test/index.js b/test/index.js index ec0777e..a5d2082 100644 --- a/test/index.js +++ b/test/index.js @@ -927,6 +927,34 @@ test("Recursion in inherited templates", function() { is(s, "override override override don't recurse", "matches expected recursive output"); }); +test("Overriden contents with nested inheritance", function() { + var child = Hogan.compile( '{{