用于在Backbone中创建列表的Handlebars模板

Handlebars template to create a list in Backbone

本文关键字:Handlebars 模板 列表 创建 Backbone 用于      更新时间:2024-04-16

我正在使用Moustach作为Rails应用程序的模板,该应用程序在前端使用Backbone.js。我能够获取正确的数据,但很难将其填充到我的列表中。这是代码。。。

articles_router.js

Rssreader.Routers.Articles = Backbone.Router.extend({
  routes: {
    '': 'index',
    'articles/:id': 'show'
  },
  initialize: function(){
    this.collection = new Rssreader.Collections.Articles();
    this.collection.fetch();
  },
  index: function(){
    var model = new Rssreader.Models.Article({collection: this.collection});
    model.fetch({
      success: function(model){
        var view = new Rssreader.Views.ArticlesIndex({model: model});
        $('#articles').html(view.render().el);
        // console.log(view.render().el);
      }
    });
  }
});

articles_index.js

Rssreader.Views.ArticlesIndex = Backbone.View.extend({
  template: JST['articles/index'],
  initialize: function(){
    this.render();
  },
  render: function(){
    this.$el.html( this.template(this.model.toJSON()) );
    console.log(this.model.toJSON({}));
    return this;
  }
});

这是article.js 中的模型

Rssreader.Models.Article = Backbone.Model.extend({
  urlRoot: '/articles',
  defaults: {
    "name": "default name",
    "summary": "default summary",
    "url": "default url",
    "published_at": "default published date",
    "guid": "default guid"
  }
});

这是模板。

<ul class="article_list">
  {{#articles}}
  <li>{{name}}</li>
  {{/articles}}
</ul>

我已经尝试了这个模板的多次迭代,但它似乎没有打印任何内容。但是,我可以在调用模板之前console.log要遍历的数据,这样我就知道它有数据了。

有什么建议吗?

您可以使用Handlebars #each助手(如果您有{articles: [{name: '1'}]})或创建自己的助手(如果你有[{name: '1'}]):

Handlebars.registerHelper('articles', function(context, options) {
  var ret = "";
  for(var i=0, j=this.length; i<j; i++) {
    ret = ret + options.fn(this[i]);
  }
  return ret;
});

模板本身就像你的模板:

<ul class="article_list">
  {{#articles}}
  <li>{{name}}</li>
  {{/articles}}
</ul>

编辑

在您的代码中,您使用了文章的集合,使用Handlebars #each:

<ul class="article_list">
  {{#each collection}}
    <li>{{name}}</li>
  {{/each}}
</ul>

您正在用集合实例化ArticlesView,然后尝试渲染模型。

有几种不同的方法可以迭代集合并渲染其模型,但最接近的方法是:

  render: function(){
    this.$el.html( this.template({articles: this.collection.toJSON()}) );
    console.log(this.collection.toJSON());
    return this;
  }

以及类似的模板

<ul class="article_list">
  {{#each articles}}
  <li>{{name}}</li>
  {{/each}}
</ul>