2

I Have a layout which is effectively structured as below

<ul class="row">
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
</ul>

What i would like is that for every 5th item a new row to be created with a class of "row" so that my code can look as shown below

<ul class="row">
    <li>content</li>
    <li>content</li>
    <li>content</li>
    <li>content</li>
<li>content</li>
</ul>
<ul class="row">
    <li>content</li>
    <li>content</li>
</ul>

Can anyone advise how this could be accomplished using a handlebars helper?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49

1 Answers1

5

You could create a wrapping helper that splits the array of rows in the desired number of elements:

// attr : name of the attribute in the current context to be split, 
//        will be forwarded to the descendants
// count : number of elements in a group
// opts : parameter given by Handlebar, opts.fn is the block template
Handlebars.registerHelper('splitter', function (attr, count, opts) {
    var context, result, arr, i, zones, inject;

    context = this;
    arr = context[attr];
    zones = Math.ceil(arr.length / count);

    result="";
    for (i = 0; i < zones; i++) {
        inject = {};
        inject[attr] = arr.slice(i * count, (i + 1) * count);

        result += opts.fn(inject);
    }

    return result;
});

Assuming your data is passed as { rows: [ {text: "Row 1"}, ... ] }, a template could look like this

{{#splitter "rows" 5}}
    <ul class='row'>
        {{#each rows}}
        <li>{{text}}</li>
        {{/each}}
    </ul>
{{/splitter}}

And a Fiddle to play with http://jsfiddle.net/HwJ6s/

nikoshr
  • 32,926
  • 33
  • 91
  • 105