1

I am trying to iterate over a backbone collection object and print one of it's attributes into a unlinked list on a haml-coffee template (.hamlc).

In context, I have a collection of fonts. I want to print the name of each font onto the template.

This is how imagine the code is going to look:

%ul
  - for font in @fonts
    %li
      = font.name

However, this does not iterate at all. I can put any input in this for loop and it simply doesn't execute.

This is what @fonts looks like when output to the console.log

Object {0: Object, 1: Object, 2: Object, 3: Object, 4: Object…}
0: Object
_id: "50bed321dbc554c7a0000005"
data: Object
name: "Actor"
user_ids: Array[0]
__proto__: Object
1: Object
2: Object
3: Object

How do I iterate over this object and output and print each name in the template?

2 Answers2

0

It seems you should specify which attribute of @fonts collection you are about to display like this :

%ul
 - for font in @fonts.name
   %li
     = font

If you'd like to iterate over object or collection you use :

- for name, location of @fonts
  = name + "lives in" + location

(for example, in case your fonts object has name and location properties)

In your code just replace 'in' with 'of' .

R Milushev
  • 4,295
  • 3
  • 27
  • 35
0

Suppose your collection looks like this

var fonts = new Backbone.Collection;
fonts.add([
    { name: 'arial'},
    { name: 'arial black'},
    { name: 'comic sans ms'}]);

You cannot just get the name of the first model in your collection with

font = fonts.first()
font.name               // <--- undefined

The reason is because Backbone models don't let you manipulate attributes directly. They have setters and getters.

font.get 'name'         // 'arial'

But back to the point, your template is fine and you only need to pass it a JSON representation of the collection

var html = window.HAML.test({fonts:fonts.toJSON()});
document.getElementById('out').innerHTML = html;

If for whatever reason, you dont want to pass it the JSON representation, you can pass it the array of models {fonts: fonts.models} but then you'd have to modify your template and have something like %li = font.get 'name'

Here's a jsfiddle (the first part is the code produced by coffee-haml) http://jsfiddle.net/jaimem/qRMqu/2/

jaime
  • 41,961
  • 10
  • 82
  • 52