在Rails,Backbone和Mustache中使用JSON - 格式似乎有所不同

Ani*_*ham 5 json ruby-on-rails mustache backbone.js

我正在尝试将一个Rails应用程序与backbone.js和小胡子模板组合在一起.我发现骨干网所需的JSON与Mustache所需的JSON不兼容.(我开始按照本教程Cloudedit -a backbone.js教程通过示例,但我想在他使用JST的地方使用Mustache.

对于主干,我们必须设置ActiveRecord :: Base.include_root_in_json = false.对于我的模型(名字和姓氏的人),来自/ people的rails发送的数据如下所示:

[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]
Run Code Online (Sandbox Code Playgroud)

我的胡子模板看起来像这样:

<h3><a href='#new'>Create New</a></h3>
<h4>People</h4>
<ul>
{{#people}}
<li>{{firstname}} {{surname}}</li>
{{/people}}
</ul>
Run Code Online (Sandbox Code Playgroud)

从小胡子文档我希望它想看到的是

{"people":[{"firstname":"Jane","surname":"Jones"},{"firstname":"Janet","surname":"Jensen"}]}
Run Code Online (Sandbox Code Playgroud)

编辑我将JS集合转换回JSON并发送给Mustache.不需要这样做.Mustache.js期望看到js对象,而不是JSON字符串.

当我到Mustache.to_html时,我有一个模型的骨干集合.模型具有firstnamesurname属性.在firebug中看起来像这样:

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"}
Run Code Online (Sandbox Code Playgroud)

这里似乎有几个问题.1.没有提到收藏品的名称(人).我可以通过各种方式解决这个问题,至少在模板中使用{{#models}} .. {{/ models}}.

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

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

Ani*_*ham 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);
Run Code Online (Sandbox Code Playgroud)

但感觉这种跳圈似乎没有必要。我会检查车把是否提供更好的东西。