5

我正在尝试用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 时,我有一个模型的骨干集合。这些模型具有属性firstnamesurname。在萤火虫中看起来像这样:

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}}。

  1. 这些属性比 Mustache.js 看起来更深。当它开始尝试在对象中查找 'firstname' 标记时,它会查找 object['firstname'] 并没有找到它,但 object.attributes['firstname'] 具有正确的值。

看来我在这里都搞混了....那我做错了什么?我该如何解决?

4

2 回答 2

2

我现在有一个解决方案(感谢这个问题)。

jsonForTemplate = JSON.parse(JSON.stringify(this.people)); //this works for a single item
context['people']=jsonForTemplate;    //need to add this for a collection
out = Mustache.to_html(tpl,context);

但感觉好像这种跳跃式的圈套是不必要的。我会检查车把是否提供更好的东西。

于 2011-07-03T10:30:42.877 回答
2

一个更简单的解决方案是toJSON在此处记录的 Collection 上使用 - http://documentcloud.github.com/backbone/#Collection-toJSON

out = Mustache.to_html(tpl, collection.toJSON);
于 2012-01-19T20:30:57.063 回答