关于json:Handlebars Block Helper:每个都有排序

Handlebars Block Helper : each with sort

我有一个使用Handlebars模板输出的json对象数组;我目前正在使用{{#each object}} ... {{/ each}}。我现在需要按对象的属性之一对对象进行排序,再次使用车把帮手也没问题


最简单的方法是在数据到达Handlebars之前对其进行排序,然后您可以照常使用{{#each ...}}且不需要帮助程序。这种方法在Handlebars中很常见,模板通常分为两部分:用于数据处理/重新安排的(Java | Coffee)脚本部分和适当的模板。

顺便说一句,您将需要调整比较器函数的行为属性。从精美的手册中:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b 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, sort b to a lower index than a.

因此,如果a.sort_indexb.sort_index相同,则要返回0,如下所示:

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

如果必须在模板内进行排序,则需要添加一个自定义的each_with_sort帮助程序来进行排序和迭代,如下所示:

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/