我有一个使用 Handlebars 模板输出的 json 对象数组;我目前正在使用 {{#each object}}...{{/each}}。我现在需要通过对象的一个属性对对象进行排序,这再次使用 Handlebars 助手和 CoffeeScript 没有问题,但是,我的模板中有一个问题,因为我无法弄清楚如何使用每个来迭代排序的数组.
到目前为止,我的研究表明我可能需要编写一个自定义的 Handlebars 助手,它实际上是:
{{#each_with_sort array}}
我现有的排序助手是这样的
Handlebars.registerHelper sort_me =>
myArray.sort (a,b)->
return if +a.sort_index >= +b.sort_index then 1 else -1
但是,我很难在模板中使用排序数组 - 例如,它并不像
{{#each sort_me(myArray)}}
数据来自第三方 API,所以我必须在 Handlebars / CoffeeScript 中执行排序。
最佳答案
最简单的做法是在数据到达 Handlebars 之前对其进行排序,然后您可以使用 {{#each ...}}
像往常一样,不需要助手。这种方法在 Handlebars 中很常见,模板通常分为两部分:用于数据修改/重新排列的 (Java|Coffee) 脚本部分和模板本身。
顺便说一句,您需要调整比较器函数来表现属性。来自 fine manual :
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
.
所以你想返回
0
如果 a.sort_index
和 b.sort_index
是一样的,更像这样: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
helper 进行排序和迭代,如下所示:# 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
)
你的模板会是这样的:
{{#each_with_sort array "sort_index"}}
...
{{/each_with_sort}}
演示:http://jsfiddle.net/ambiguous/zusq2tt4/
关于json - Handlebars block 助手 : each with sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662031/