您可以将集合转换为json并将其传递给模板并访问模型。通过这种方式,您可以使用_3;遍历模型。并在模板中渲染其属性。
var CommentsListView = Backbone.View.extend({
el: '.page',
render : function(){
var context = {};
this.commentsCollection = new CommentsCollection();
this.commentsCollection.fetch({
success: () => {
//var models = commentsCollection.models;
// _.each(models, function(models){
// console.log(models.get('firstname'));
// });
context['models'] = this.commentsCollection.toJSON()
var template = _.template($('#reddit-comments-template').html());
that.$el.html(template(context));
}
})
}
});
模板:
<html>
<head>
<title> </title>
</head>
<body>
<div class="container">
<h1>Top posts</h1>
<hr />
<div class="page"></div>
</div>
<script type="text/template" id="reddit-comments-template">
<table class = "comments table">
<thead>
<tr>
<th>Row</th>
<th>Commments</th>
</tr>
</thead>
<tbody>
<tr>
<% _.each(models, function(model){ %>
<tr>
<td><%= model.firstname %>
<td><%= model.lastname %></td>
<td><%= model.id %></td>
</tr>
<% }); %>
</tr>
</tbody>
</table>
</script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script type="text/javascript" src="demo.js"></script>
</body>
</html>