使用模板以表格格式显示数据
Display data in tabular format using templates
我是 Backbone.js 的新手。我有一些来自 REST 服务的数据,我想使用 Backbone.js 中的模板将它们显示为表格格式。有人可以帮助我了解如何循环并以表格格式打印数据。以下是我到目前为止所取得的成就。
型号
define(['backbone'], function(Backbone) {
var abcViewModel = Backbone.View.extend({
template: _.template($('#abc-template').html()),
render: function() {
console.log(this.model.toJSON());
data = this.model.toJSON();
var html = this.template(data);
$(this.el).html(html);
},
initialize: function() {
this.model.on('change', this.render, this);
}
});
return abcViewModel;
});
console.log(this.model.toJSON()
的输出是
HTML/Template
<script id="abc-template" type="text/template">
<%= data.incThisYear %>
<%= data.incLastYear %>
</script>
当前屏幕输出
但我想要表格格式的输出
| incThisYear | incLastYear
Jan | |
Feb | |
Mar | |
and so on..
有多种方法可以解决这个问题。最快的方法之一是在您的模板中添加一个循环,该循环将遍历一年中的每个月并显示月份,以及今年的相应公司(如果找到)和公司。去年 table:
<script id="abc-template" type="text/template">
<table>
<tr>
<th>Month</th>
<th>Inc. This Year</th>
<th>Inc. Last Year</th>
</tr>
<% ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].forEach(function(month, i) { %>
<tr>
<td>
<%= month %>
</td>
<td>
<%= incThisYear[i] || '-'%>
</td>
<td>
<%= incLastYear[i] || '-'%>
</td>
</tr>
<% }) %>
</table>
</script>
我快速整理了一个 fiddle 来展示这个动作:https://jsfiddle.net/hy8otewm/
我是 Backbone.js 的新手。我有一些来自 REST 服务的数据,我想使用 Backbone.js 中的模板将它们显示为表格格式。有人可以帮助我了解如何循环并以表格格式打印数据。以下是我到目前为止所取得的成就。
型号
define(['backbone'], function(Backbone) {
var abcViewModel = Backbone.View.extend({
template: _.template($('#abc-template').html()),
render: function() {
console.log(this.model.toJSON());
data = this.model.toJSON();
var html = this.template(data);
$(this.el).html(html);
},
initialize: function() {
this.model.on('change', this.render, this);
}
});
return abcViewModel;
});
console.log(this.model.toJSON()
的输出是
HTML/Template
<script id="abc-template" type="text/template">
<%= data.incThisYear %>
<%= data.incLastYear %>
</script>
当前屏幕输出
但我想要表格格式的输出
| incThisYear | incLastYear
Jan | |
Feb | |
Mar | |
and so on..
有多种方法可以解决这个问题。最快的方法之一是在您的模板中添加一个循环,该循环将遍历一年中的每个月并显示月份,以及今年的相应公司(如果找到)和公司。去年 table:
<script id="abc-template" type="text/template">
<table>
<tr>
<th>Month</th>
<th>Inc. This Year</th>
<th>Inc. Last Year</th>
</tr>
<% ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].forEach(function(month, i) { %>
<tr>
<td>
<%= month %>
</td>
<td>
<%= incThisYear[i] || '-'%>
</td>
<td>
<%= incLastYear[i] || '-'%>
</td>
</tr>
<% }) %>
</table>
</script>
我快速整理了一个 fiddle 来展示这个动作:https://jsfiddle.net/hy8otewm/