diff --git a/lib/handlebars/base.js b/lib/handlebars/base.js index 9f4fdb6eb..76ba00a4d 100644 --- a/lib/handlebars/base.js +++ b/lib/handlebars/base.js @@ -103,6 +103,9 @@ Handlebars.registerHelper('each', function(context, options) { if (options.data) { data = Handlebars.createFrame(options.data); + if (!data.root) { + data.root = this; + } } if(context && typeof context === 'object') { @@ -145,7 +148,13 @@ Handlebars.registerHelper('unless', function(context, options) { }); Handlebars.registerHelper('with', function(context, options) { - if (!Handlebars.Utils.isEmpty(context)) return options.fn(context); + if (!Handlebars.Utils.isEmpty(context)) { + if (options.data && !options.data.root) { + options.data = Handlebars.createFrame(options.data); + options.data.root = this; + } + return options.fn(context); + } }); Handlebars.registerHelper('log', function(context, options) { diff --git a/spec/qunit_spec.js b/spec/qunit_spec.js index fef5166bc..87eb53e90 100644 --- a/spec/qunit_spec.js +++ b/spec/qunit_spec.js @@ -241,6 +241,17 @@ test("this keyword nested inside helpers param", function() { }, Error, "Should throw exception"); }); +test("with stores root context in data.root", function() { + var helpers = { + useRoot: function(options) { + return options.data.root.foo; + } + }; + var string = "{{#each bananas}}{{#with brand}}{{.}}{{useRoot}}{{/with}}{{/each}}"; + var hash = {bananas: [{colour: "green", brand: "Monkey"}, { colour: "yellow", brand: "Baboon"}], foo: "Foo"}; + shouldCompileTo(string, [hash, helpers], "MonkeyFooBaboonFoo", "with stores root context in data.root"); +}); + suite("inverted sections"); test("inverted sections with unset value", function() { @@ -834,6 +845,17 @@ test("each with @index", function() { equal(result, "0. goodbye! 1. Goodbye! 2. GOODBYE! cruel world!", "The @index variable is used"); }); +test("each stores root context in data.root", function() { + var helpers = { + useRoot: function(options) { + return options.data.root.foo; + } + }; + var string = "{{#each bananas}}{{useRoot}}{{/each}}"; + var hash = {bananas: ["green", "yellow", "brown"], foo: "Foo"}; + shouldCompileTo(string, [hash, helpers], "FooFooFoo", "each stores root context in data.root"); +}); + test("data passed to helpers", function() { var string = "{{#each letters}}{{this}}{{detectDataInsideEach}}{{/each}}"; var hash = {letters: ['a', 'b', 'c']};