Issue rendering collection data in handlebars template

人走茶凉 提交于 2019-12-11 11:08:38

问题


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

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