Search code examples
javascriptbackbone.jsunderscore.js

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?


Solution

  • 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>
    {{ }); }}