Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/handlebars/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand Down Expand Up @@ -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) {
Expand Down
22 changes: 22 additions & 0 deletions spec/qunit_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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']};
Expand Down