Anthony
Anthony

Reputation: 2416

Underscore _.each array in template

I have a JSON with multiple objects as follows:

  {
  "taskId": 100,
  "name": "I-9 Form",
  "desc": "Form I-9",
  "dueDate": "0",
  "links": [{"link1": "http://www.uscis.gov/sites/default/files/files/form/i-9.pdf"},   {"link2": "http://www.uscis.gov/sites/default/files/files/form/i-9.pdf"}],
  "status": "Completed",
  "comments": ""
}

I want to display each link in the array in a template. I think im close with:

{{ _.each(model.links, function(link) { }}
    <div>Links: {{= link}}</div>
{{ }); }}

but this prints out

Links: [object Object] Links: [object Object]

in the dom. What do I need to do so it prints out each link?

Upvotes: 0

Views: 251

Answers (2)

mu is too short
mu is too short

Reputation: 434665

If the objects in links always have just one key/value then you can do something like this:

{{= _(link).values()[0] }}

to work around not knowing what the keys will be.

Demo: http://jsfiddle.net/ambiguous/66vY4/

Upvotes: 2

Praveen Prasannan
Praveen Prasannan

Reputation: 7123

You data structure is wrong. If it is an array you should use same key. link instead of link1 and link2. If you would like to use it as link1 and link2, the it should not be an array. Just a plain object. Then above code will work.

data structure:

{
      "taskId": 100,
      "name": "I-9 Form",
      "desc": "Form I-9",
      "dueDate": "0",
      "links": [{"link": "http://www.uscis.gov/sites/default/files/files/form/i-9.pdf"},   {"link": "http://www.uscis.gov/sites/default/files/files/form/i-9.pdf"}],
      "status": "Completed",
      "comments": ""
    }

template:

{{ _.each(model.links, function(link) { }}
    <div>Links: {{= link.link}}</div>
{{ }); }}

Upvotes: 0

Related Questions