Created
March 2, 2013 03:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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