Search code examples
javascripttemplatesunderscore.jsunderscore.js-templating

How to display a JS object with underscore templates?


I am tying to display a JS object of data using underscore templates. I can't seem to be able to work out how to drill through the object to get the country names or other date (for example tarrifType) and display it using my template. The object looks like this...

var items = [
{
"country": {
  "China": [
    {
      "tarrifType": "China Pass",
      "fixLine": "23p",

    },
    {
      "tarrifType": "Monthly plan",
      "fixLine": "3p",
    }
  ],
  "Australia": [
    {
      "tarrifType": "Pay as you go",
      "fixLine": "73p"
   },
    {
      "tarrifType": "Australia Pass",
      "fixLine": "49p",

    },
    {
      "tarrifType": "Monthly plan",
      "fixLine": "20p",

    }
  ],     
  "Nigeria": [
    {
      "tarrifType": "Pay as you go",
      "fixLine": "73p"
    },
    {
      "tarrifType": "Nigeria Pass",
      "fixLine": "49p"
    }
  ]
}

} ];

I am reading the object and binding it to a template like this it using this

 var tableTemplate = $("#table-data").html();

 $("table.outer tbody").html(_.template( tableTemplate, {items:items} ));

And I am using this underscore template...

<script type="text/html" id='table-data'>
<% _.each(items,function(item,key,list){ %>
<tr>
    <td></td>
    <td><%- item.country %></td>
</tr>
<% }) %>
</script>

So far I am not getting any errors but template renders but only displays [object Object] so i think its nearly there. I tried using dot notation (item.country) but I still need to work out how to loop through it and display. Any ideas?


Solution

  • Change

    $("table.outer tbody").html(_.template( tableTemplate, {items:items} ));
    

    to

    $("table.outer tbody").html(_.template( tableTemplate, {items:items.country} ));
    

    and also change

    <td><%- item %></td>
    

    to

    <td><%- country[key].tarrifType %></td>
    

    Items has a single property: country. Instead of calling the template with items, call it with items.country. Since you have the key in your loop, you can access the object in each iteration. Each object also returns an array of tarrifTypes etc. So you may/may not need to iterate these too.

    I also created this fiddle. Although it is not directly relevant with _ templates, it may still give you an idea how to iterate through JS object.

    Cheers, =]