json - Handlebars block 助手 : each with sort

标签 json coffeescript handlebars.js

我有一个使用 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. 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.


所以你想返回0如果 a.sort_indexb.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/

相关文章:

javascript - 带有替换函数的 JSON.stringify 中的奇怪行为

jquery - jquery-select2 的依赖下拉内容

jquery - 测试简单复选框功能的 jquery 更改

javascript - 让 javascript 仅作用于列表中的一项

javascript - 从 POST 请求中解析 req.body

javascript - 如何在不使用 {{#each}} 或 {{#if}} 的情况下从 Handlebars.js 中的 .json 文件获取数据?

php - 如何使用 json_encode 从 php 获取数据到 javascript?

php - 如何在 jQuery 上循环遍历这个 JSON 数组?

javascript - {{#each}} 内的 Handlebars 助手

javascript - meteor 铁路由器 header 类型不是 json