Skip to content Skip to sidebar Skip to footer

How Can I Create Conditional Row Classes Using Handlebars.js?

I Have a layout which is effectively structured as below
  • content
  • content
  • content

Solution 1:

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

Post a Comment for "How Can I Create Conditional Row Classes Using Handlebars.js?"