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.
Your JavaScript to CoffeeScript transliteration is broken. You don’t use
for ... into iterate over an object in CoffeeScript, you usefor k, v of ...:This CoffeeScript loop:
becomes this JavaScript:
So if
yis an object without alengthproperty, then_lenwill beundefinedand the JavaScriptfor(;;)loop won’t iterate at all.You should also be using
owninstead ofhasOwnProperty: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 oor the equivalent form:if
expris 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:
Demo: http://jsfiddle.net/ambiguous/LWTPv/