Handlebars and MeteorJs for every other or number

断了今生、忘了曾经 提交于 2019-12-24 12:06:30

问题


I'm trying to create a Handlebars.registerHelper() that would wrap my {{>template}} in an {{each items}} for every number I enter.

So something like this;

{{forevery items 4}}
    {{> item_row_template}}
{{/forevery}}

The desired result would be for every 4 items wrap it around a div.

<div class="row">
    <div class="item_1">item</div>
    <div class="item_2">item</div>
    <div class="item_3">item</div>
    <div class="item_4">item</div>
</div>

<div class="row">
    <div class="item_1">item</div>
    <div class="item_2">item</div>
    <div class="item_3">item</div>
    <div class="item_4">item</div>
</div>

etc...


回答1:


what you want to do is create a helper that will iterate over the list and manually append the divs every so often.

Here is an example:

Handlebars.registerHelper('forevery', function(context, limit, options) {
    var ret = "";
    if (context.length > 0) {
        ret += "<div>";
        for(var i=0, j=context.length; i<j; i++) {
            ret = ret + options.fn(context[i]);
            if ( (i+1) % limit === 0 ) {
                ret += "</div><div>";
            }
        }
        ret += "</div>";
    }
    return ret;
});

This function will loop through the array of items and every nth row it will close a div and open a new one. So this would be called like:

{{#forevery items 3}}
    {{> item_row_template}}
{{/forevery}}

Hope this helps :)



来源:https://stackoverflow.com/questions/16631395/handlebars-and-meteorjs-for-every-other-or-number

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