Backbone.js 木偶;CompositeView-如何呈现自定义表标题

Backbone.js 木偶;CompositeView-如何呈现自定义表标题,backbone.js,marionette,Backbone.js,Marionette,我是新来的木偶,喜欢它。我创建了一个ItemView和CompositeView来显示集合中的值。这很好,但我想呈现自定义字段/列标题。我已经使用Backbone.Collection和u.each(item.keys()、function(key){…完成了这项工作,但我不能使用木偶技术,因为我对每一行都使用ItemView 我尝试过使用appendHTML,但访问该集合时遇到困难。以下是我目前获得的结果: ... render: function () { var template

我是新来的木偶,喜欢它。我创建了一个ItemView和CompositeView来显示集合中的值。这很好,但我想呈现自定义字段/列标题。我已经使用Backbone.Collection和u.each(item.keys()、function(key){…完成了这项工作,但我不能使用木偶技术,因为我对每一行都使用ItemView

我尝试过使用appendHTML,但访问该集合时遇到困难。以下是我目前获得的结果:

...
render: function () {
    var template = "<% _.each(item.keys(), function(key){%><th><%= key %></th><%})%>";
    this.$("thead").html(_.template(template, {
        item: this.collection.models[0]
    }));
},
appendHtml: function (collectionView, itemView) {
    collectionView.$("tbody").append(itemView.el);
},
...
。。。
渲染:函数(){
var模板=”;
这个.$(“thead”).html(u.template(template{
项目:此.collection.models[0]
}));
},
appendHtml:函数(collectionView、itemView){
collectionView.$(“tbody”).append(itemView.el);
},
...

这不起作用。请提供任何帮助。

您可以在此compositeView中存储额外数据,然后在模板中使用。请允许我使用下面的CoffeeScript

步骤1:获取数据并将其存储在上下文变量中,例如
this.headers

initialize: ->
  @headers = @collection.last().attributes.keys
templateHelpers ->
  view = @ # Use this line because context will change below
  headers: ->
    view.headers
步骤2:使用内置的
templateHelpers

initialize: ->
  @headers = @collection.last().attributes.keys
templateHelpers ->
  view = @ # Use this line because context will change below
  headers: ->
    view.headers
步骤3:用简单的迭代在模板中显示它。我将使用Handlerbars作为例子

<table>
  <thead>
    <tr>
      <th>Records</th>
      {{#each headers}}
        <th>{{this}}</th>
      {{/each}}
    </tr>
  </thead> 
  <tbody>
    <!-- Display itemViews here-->
  </tbody>
</table>

记录
{{{#每个头}}
{{this}}
{{/每个}}

谢谢你的回复。我理解你的方法。使用.last()和TemplateHelper是我不知道的模式。另一方面,我仍然感到困惑。sub-ItemView将tbody呈现得很好。在父CompositeView中,似乎是“this.headers=this.collection.last().keys()'不起作用。我使用dev工具仔细检查了代码,似乎.last()不是这个集合的有效方法。有什么想法吗?@JoseLopez,集合应该能够使用
last()
这是主干借用的下划线方法。原因可能是集合尚未准备就绪,请检查此时集合是否有效。如果无效,则需要手动将集合分配为
@collection=options。collection
(options作为初始化参数)在查询最后一个之前。顺便说一下,
键不应该直接作用于模型实例。它应该在
属性上。我已经更新了答案。