How can I create conditional row classes using Handlebars.js?

余生长醉 提交于 2019-12-10 22:17:11

问题


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?


回答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 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/



来源:https://stackoverflow.com/questions/11826997/how-can-i-create-conditional-row-classes-using-handlebars-js

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