Skip to content

Instantly share code, notes, and snippets.

@cmather
Created March 2, 2013 03:15
Show Gist options
  • Save cmather/5069533 to your computer and use it in GitHub Desktop.
Save cmather/5069533 to your computer and use it in GitHub Desktop.
Example of monkey patching Handlebars 'each' method in Meteor to give access to a parent data context inside a child template helper.
if (Meteor.isClient) {
_.extend(Handlebars._default_helpers, {
'each': function (data, options) {
var parentData = this;
if (data && data.length > 0) {
return _.map(data, function (childContext, idx) {
var branch = (childContext._id || (typeof childContext === 'string' ? childContext : null) ||
Spark.UNIQUE_LABEL);
return Spark.labelBranch(branch, function () {
// won't work if childContext is a string because
// can't add methods to a string literal.
if (_.isObject(childContext)) {
childContext._parentData = parentData || {};
}
return options.fn(childContext);
});
}).join('');
} else {
return Spark.labelBranch('else', function () {
return options.inverse(parentData);
});
}
}
});
Template.list.helpers({
parentContext: {
title: "Parent Context"
},
items: function () {
return [{name: "Child Context One"}, {name: "Child Context Two"}]
}
});
Template.listItem.helpers({
test: function () {
console.log(this, arguments);
return "";
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment