问题
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