Handlebars Block Helper : each with sort
我有一个使用Handlebars模板输出的json对象数组;我目前正在使用{{#each object}} ... {{/ each}}。我现在需要按对象的属性之一对对象进行排序,再次使用车把帮手也没问题
最简单的方法是在数据到达Handlebars之前对其进行排序,然后您可以照常使用
顺便说一句,您将需要调整比较器函数的行为属性。从精美的手册中:
If
compareFunction is supplied, the array elements are sorted according to the return value of the compare function. Ifa andb are two elements being compared, then:
- If
compareFunction(a, b) is less than 0, sorta to a lower index thanb , i.e. a comes first.- If
compareFunction(a, b) returns 0, leavea andb unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.- If
compareFunction(a, b) is greater than 0, sortb to a lower index thana .
因此,如果
1 2 3 4 5 6 | myArray.sort (a,b)-> a = +a.sort_index b = +b.sort_index return 1 if a > b return 0 if a == b return -1 if a < b |
如果必须在模板内进行排序,则需要添加一个自定义的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # If you're always sorting by sort_index then you don't need the key argument # and you might want to put the '+'-casting back in. Handlebars.registerHelper('each_with_sort', (array, key, opts) -> data = Handlebars.createFrame(opts.data) if(opts.data) array = array.sort (a, b) -> a = a[key] b = b[key] return 1 if a > b return 0 if a == b return -1 if a < b s = '' for e, i in array data.index = i if(data) # Support the usual @index. s += opts.fn(e, data: data) s ) |
,您的模板将如下所示:
1 2 3 | {{#each_with_sort array"sort_index"}} ... {{/each_with_sort}} |
演示:http://jsfiddle.net/ambiguous/zusq2tt4/