与Backbone.js的Mustache.js / Hogan.js

我正在尝试使用backbone.js实现一些代码

和hogan.js(http://twitter.
github.com/hogan.js/)

Hogan.js was developed against the mustache test suite,
so everything that holds true for templates as
specified here, is also the case for hogan.js.

我的问题是将Backbone.Collection传递给Hogan / Mustache.

对于这样的简单模板:

{{name}}

Hogan / Mustache期待这样的事情很好:

{"name":"How Bizarre","artist":"OMC"}

但是我的Backbone.Collection是:

一个)
    [{“name”:“如何奇怪”,“艺术家”:“OMC”}]

或这个:

b)
    [{“name”:“How howarre”,“artist”:“OMC”},{“name”:“Sexual Healing”,“artist”:“Marvin Gaye”}]

从演示页面http://mustache.github.com/#demo我不能
迭代a)或b)Backbone.Collection obejcts中的任何一个.

任何人都可以指出我怎么做到这一点?

var Song = Backbone.Model.extend({
defaults: {
name: "Not specified",
artist: "Not specified"
}
});

var Album = Backbone.Collection.extend({
model: Song
});

var song1 = new Song({ name: "How Bizarre", artist: "OMC" });
var song2 = new Song({ name: "Sexual Healing", artist: "Marvin Gaye" });

var myAlbum = new Album;

myAlbum.add(song1);
myAlbum.add(song2);

我通过传递我的Backbone.Colleciton传递尝试渲染
像这样的对象:myAlbum.toJSON()

var template = "{{name}}!";

var template = Hogan.compile(template);

this.el.html(template.render(myAlbum.toJSON()));

谢谢.

最佳答案 看起来你正在将一个Collection传递给Hogan而不是一个单独的模型.

试试这个:

_.each(myAlbum,function(album) {
    this.el.append(template.render(album.toJSON()));
});
点赞