handlebars.js - Get first item in a sorted collection -
assuming have like:
{{#each pageelements}} {{#is pageelement "news"}} {{#withsort pages "data.posted" dir="desc"}} <a href="/{{relativelink}}"> {{formatdate data.posted "%d.%m.%y"}}: {{data.title}} </a> {{/withsort}} {{/is}} {{/each}}
how show first item withsort
spits out?
i'm think can use first
collection helper (http://assemble.io/helpers/helpers-collections.html) haven't been able syntax right.
the helpers in handlebars-helpers built grunt-assemble
don't handle of things you'd want specific case.
we're working on getting dev branch published , of these easier use handlebars subexpressions.
for now, want make own helper sorting, can use first
:
make sort.js
helper file:
var = require('get-value'); module.exports = function sort(array, field, options) { var arr = clonearray(array); if (typeof options === 'undefined') { options = field; field = null; arr = arr.sort(); } else { arr = arr.sort(sortby(field)); } if (options.hash && options.hash.dir === 'desc') { arr = arr.reverse(); } return arr; }; function clonearray(arr) { var len = arr.length, = 0; var results = new array(len); while(i++ < len) { results[i] = arr[i++]; } return results; } function sortby(prop) { return function(a, b) { var aval = get(a, prop); var bval = get(b, prop); if (aval > bval) { return 1; } else { if (aval < bval) { return -1; } } return 0; } }
register helper assemble , use in template:
{{#each pageelements}} {{#is pageelement "news"}} {{#withfirst (sort pages "data.posted" dir="desc")}} <a href="/{{relativelink}}"> {{formatdate data.posted "%d.%m.%y"}}: {{data.title}} </a> {{/withfirst}} {{/is}} {{/each}}
this should need. hope helps.
Comments
Post a Comment