问题
I want to render collection in handlebars precompiled templates,
this.courses.fetch() is working
handlebars view is rendering correctly...(only each loop not rendering collection data)
here is my code...
router.js
App.Router = Backbone.Router.extend({
routes: {
'master/courses' : 'courses'
},
initialize: function(){
this.courses = new App.Collections.Courses();
this.list = new App.Views.List( {collection: this.courses} );
},
courses: function() {
$('#page').html(this.list.render().el);
}
});
var app = new App.Router();
Backbone.history.start();
courses.js
App.Collections.Courses = Backbone.Collection.extend({
model: App.Models.Course,
url: '/api/courses'
});
list.js
p.Views.List = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'reset', this.render);
},
render:function(){
this.$el.html( Handlebars.templates.list(this.collection) );
return this;
}
});
list.handlebars
<h1>Courses</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
{{#each models}}
<td>{{attributes.id}}</td>
<td>{{attributes.name}}</td>
{{/each}}
</tr>
</tbody>
</table>
this is my first attempt on backbone project kindly suggest good practice also
回答1:
I don't see here the point where collection fetching is fired. The first line in your courses probably should be this.collection.fetch({ reset: true });
As I see in provided HTML structure, each should be before tr tag. Like this:
<h1>Courses</h1>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{{#each models}}
<tr>
<td>{{attributes.id}}</td>
<td>{{attributes.name}}</td>
</tr>
{{/each}}
</tbody>
</table>
来源:https://stackoverflow.com/questions/21644095/issue-rendering-collection-data-in-handlebars-template