backbone.js - Mustache.js/Hogan.js 和 Backbone.js

标签 backbone.js mustache

我正在尝试使用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":"How Bizarre","artist":"OMC"}]

或这个:

b)
[{"name":"How Bizarre","artist":"OMC"}, {"name":"Sexual Healing","artist":"Marvin Gaye"}]

来自演示页面 http://mustache.github.com/#demo我不能
迭代 a) 或 b) Backbone.Collection 对象。

谁能指出我如何做到这一点?
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()));
});

关于backbone.js - Mustache.js/Hogan.js 和 Backbone.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8792490/

相关文章:

python - : Django-rest-Framework 处的断言错误

ruby - Mustache & Sinatra - 是否可以省略 view.rb 文件?

javascript - 如何在 mustache.js 演示页面上使用 lambda?

javascript - 在 mustache 模板中通过数组键选择项目?

javascript - Backbone JS单页应用文件上传?

javascript - 主干 POST JSON

javascript - requirejs:模块名称 "underscore"尚未加载上下文

backbone.js - Backbone.Model.Initialize 中的属性和选项有什么区别

javascript - Backbone.js:将事件类应用于模板中的事件元素?

ruby-on-rails - Rails 3.1 模板处理程序