Handlebars helper which allows you to group lists by a property of each item.
With Node.js:
$ npm install handlebars-group-by
With Bower:
$ bower install shannonmoeller/handlebars-group-by
Helpers are generated by passing in your instance of Handlebars. This allows you to selectively register the helpers on various instances of Handlebars.
handlebars
Handlebars
- An instance of Handlebars.
Generates an object containing the helper suitible for passing into registerHelper
.
var handlebars = require('handlebars'),
groupBy = require('handlebars-group-by');
handlebars.registerHelper(groupBy(handlebars));
handlebars
Handlebars
- An instance of Handlebars.
Both generates an object containing the helper and registers it with Handlebars automatically.
var handlebars = require('handlebars'),
groupBy = require('handlebars-group-by');
groupBy.register(handlebars);
list
Array
- Array whose items should be grouped together.by
String
- The name of the property by whose value items should be grouped.
Data:
{
posts: [
{ date: { year: 2014 }, title: 'foo', body: 'foo bar' },
{ date: { year: 2015 }, title: 'bat', body: 'bat qux' },
{ date: { year: 2014 }, title: 'bar', body: 'bar baz' },
{ date: { year: 2014 }, title: 'baz', body: 'baz bat' },
{ date: { year: 2015 }, title: 'qux', body: 'qux foo' }
]
}
Template:
{{#group posts by="date.year"}}
<h1>{{ value }}</h1>
{{#each items}}
<h2>{{ title }}</h2>
<p>{{ body }}</p>
{{/each}}
{{/group}}
Output:
<h1>2014</h1>
<h2>foo</h2>
<p>foo bar</p>
<h2>bar</h2>
<p>bar baz</p>
<h2>baz</h2>
<p>baz bat</p>
<h1>2015</h1>
<h2>bat</h2>
<p>bat qux</p>
<h2>qux</h2>
<p>qux foo</p>
Standards for this project, including tests, code coverage, and semantics are enforced with a build tool. Pull requests must include passing tests with 100% code coverage and no linting errors.
$ npm test
MIT © Shannon Moeller