Iterating over javascript objects with handlebars

陌路散爱 提交于 2019-12-07 12:30:15

问题


I am trying to register helpers with Handlebars to allow iterating over JSON objects. This gist looked like an appropriate solution. I converted that into the following CoffeeScript. Nothing seems to happen when I use either of the helpers (that holds true for both vanilla JavaScript and the CoffeeScript version). Any ideas?

$ ->
  Handlebars.registerHelper "key_value", (obj, fn)->
    buffer = ""
    key 
    for key in obj 
      if obj.hasOwnProperty(key)
        buffer += fn({key: key, value: obj[key]})
    buffer

  Handlebars.registerHelper "each_with_key", (obj, fn)->
    context
    buffer = ""
    key 
    keyName = fn.hash.key
    for key in obj 
      if obj.hasOwnProperty(key)
        context = obj[key]
        if keyName
          context[keyName] = key 
          buffer += fn(context)
    buffer

In the template:

{{#key_value categories}}
I'M ALIVE!!
{{/key_value}}

{{#each_with_key categories key="category_id"}}
I'M ALIVE!!
{{/each_with_key}}

I am currently using gem 'handlebars-assets' in the Gemfile to add handlebars to a rails app.


回答1:


Your JavaScript to CoffeeScript transliteration is broken. You don't use for ... in to iterate over an object in CoffeeScript, you use for k, v of ...:

Use of to signal comprehension over the properties of an object instead of the values in an array.

This CoffeeScript loop:

for x in y
    ...

becomes this JavaScript:

for (_i = 0, _len = y.length; _i < _len; _i++) {
  x = a[_i];
  ...
}

So if y is an object without a length property, then _len will be undefined and the JavaScript for(;;) loop won't iterate at all.

You should also be using own instead of hasOwnProperty:

If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be interited from the prototype, use for own key, value of object.

but that's more for convenience than correctness.

Also, CoffeeScript loops are expressions so you'd usually say array = expr for own k, v in o or the equivalent form:

array = for own k, v in o
    expr

if expr is more than one line or too long to allow for a readable comprehension.

A correct and more idiomatic version of your helpers in CoffeeScript would look more like this:

Handlebars.registerHelper "key_value", (obj, fn)->
    (fn(key: key, value: value) for own key, value of obj).join('')

Handlebars.registerHelper "each_with_key", (obj, fn)->
    key_name = fn.hash.key
    buffer   = for own key, value of obj
        value[key_name] = key
        fn(value)
    buffer.join('')

Demo: http://jsfiddle.net/ambiguous/LWTPv/



来源:https://stackoverflow.com/questions/9102068/iterating-over-javascript-objects-with-handlebars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!