问题
Until version 0.8 it was possible to use the regular Handlebars way for defining iterative block helpers such as the popular each_with_key
, defined, e.g., here as follows:
Handlebars.registerHelper("each_with_key", function(obj, fn) {
var context,
buffer = "",
key,
keyName = fn.hash.key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
context = obj[key];
if (keyName) {
context[keyName] = key;
}
buffer += fn(context);
}
}
return buffer;
});
This no longer works in 0.8, and neither the migration guide nor the spacebars documentation show an example for this.
Given that block helpers are now treated like inclusions, and inclusions need to return a template (or null), instead of HTML, I'm sort of clueless as to whether and how this is even possible at this point.
回答1:
And just as I was about to give up, I figure it out. It's in fact easier and prettier now in 0.8 than it was before. The following seems to work great:
JS:
UI.registerHelper('addKeys', function (all) {
return _.map(all, function(i, k) {
return {key: k, value: i};
});
});
HTML:
{{#each addKeys obj}}
<div>
{{key}}: {{value}}
</div>
{{/each}}
来源:https://stackoverflow.com/questions/22750022/defining-iterative-block-helpers-in-meteor-0-8