如何使用下划线模板显示JS对象?

时间:2015-06-24 11:01:02

标签: javascript templates underscore.js underscore.js-templating

我想用下划线模板显示数据的JS对象。我似乎无法弄清楚如何钻取对象以获取国家/地区名称或其他日期(例如tarrifType)并使用我的模板显示它。该对象看起来像这样......

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"
    }
  ]
}

}        ];

我正在阅读该对象并使用此

将其绑定到这样的模板
 var tableTemplate = $("#table-data").html();

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

我正在使用这个下划线模板......

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

到目前为止,我没有得到任何错误,但模板渲染,但只显示[对象对象]所以我认为它几乎在那里。我尝试使用点符号(item.country),但我仍然需要弄清楚如何循环并显示。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

更改

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

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

并且还要改变

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

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

项目只有一个属性:country。不是使用项目调用模板,而是使用items.country调用它。由于循环中有键,因此可以在每次迭代中访问该对象。每个对象也返回一个tarrifTypes等数组。所以你可能/可能不需要迭代这些。

我还创建了this fiddle。虽然它与_ templates没有直接关系,但它仍然可以让你知道如何遍历JS对象。

干杯,=]