I have an object which on passing to Handlebars template, it iterates on default sort, but I want to sort in a particular way and not the default way. The way I tried this is like :-
<div id="some-stuff"></div>
<script id="some-template" type="text/x-handlebars-template">
<ul>
{{#test this}}{{/test}}
</ul>
</script>
Helper
Handlebars.registerHelper('test', function(obj, options) {
var sortIn = ['red', 'green', 'blue', 'yellow'];
var rt = '';
sortIn.forEach(function(entry) {
for (var i = 0; i < obj[entry].length; i++) {
rt += '<li><span>' + obj[entry][i] + '</span></li>';
}
});
return rt;
});
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = { // want output as red, green, blue and yellow
'yellow': ['Yellow', 1, 2, 3, 4, 5],
'green': ['Green', 1, 2, 3, 4, 5],
'blue': ['Blue', 1, 2, 3, 4, 5],
'red': ['Red', 1, 2, 3, 4, 5]
};
var html = template(data);
$("#some-stuff").html(html);
But for some reason, I am not happy with this, at the end, it's me who is looping and passing elements to the template. What can I do to loop this by default in the sortIn
order without helper using #each
.
Somewhat similar to this question - Sort object keys with Handlebars