Defining iterative block helpers in Meteor 0.8

谁说我不能喝 提交于 2019-12-01 10:49:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!