Perspective
Perspective

Reputation: 632

Handlebars and MeteorJs for every other or number

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...

Upvotes: 1

Views: 580

Answers (1)

Gabriel M.
Gabriel M.

Reputation: 31

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 :)

Upvotes: 2

Related Questions