我正在尝试用backbone.js 和mustache 模板组合一个Rails 应用程序。我发现主干所需的 JSON 与 Mustache 所需的 JSON 不兼容。(我开始通过示例学习本教程Cloudedit -abone.js 教程,但我想在他使用 JST 的地方使用 Mustache。
对于骨干网,我们必须设置 ActiveRecord::Base.include_root_in_json = false。对于我的模型(有名字和姓氏的人),rails 从 /people 发送的数据如下所示:
[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]
我的小胡子模板如下所示:
<h3><a href='#new'>Create New</a></h3>
<h4>People</h4>
<ul>
{{#people}}
<li>{{firstname}} {{surname}}</li>
{{/people}}
</ul>
从小胡子文档中,我希望它想看到的是
{"people":[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]}
编辑我将 JS 集合转换回 JSON 并发送到 Mustache。不需要那样做。Mustache.js 期望看到 js 对象,而不是 JSON 字符串。
当我到达 Mustache.to_html 时,我有一个模型的骨干集合。这些模型具有属性firstname和surname。在萤火虫中看起来像这样:
collection
+_byCid
+_byId
length 2
- models [object { attributes=(...), more...}, object {attributes=(...), more...}]
- 0 object { attributes=(...), more...}
....... some more properties of the object
+ attributes object {firstname="Janet", surname="Jensen"}
这里似乎有几个问题。1. 没有提及收藏(人)的名称。我猜我可以通过各种方式解决这个问题,至少通过在模板中使用 {{#models}}..{{/models}}。
- 这些属性比 Mustache.js 看起来更深。当它开始尝试在对象中查找 'firstname' 标记时,它会查找 object['firstname'] 并没有找到它,但 object.attributes['firstname'] 具有正确的值。
看来我在这里都搞混了....那我做错了什么?我该如何解决?