How to display a JS object with underscore templates?

▼魔方 西西 提交于 2019-12-22 10:28:45

问题


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?


回答1:


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, =]



来源:https://stackoverflow.com/questions/31024786/how-to-display-a-js-object-with-underscore-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!