如何动态构造复合视图的模板

时间:2013-07-16 09:29:40

标签: javascript html backbone.js marionette

期望的输出:

  <script id="table-template" type="text/html">
      <table>
        <thead>
           ADD THE HEADER NAMES HERE DYNAMICALLY,
        </thead>        
        <!-- insert collection items -->
        <tbody></tbody>
      </table>
    </script>

我正在尝试生成上面的模板,这里的问题是标题名称

        投资组合         量         交换         Fccy中的金额         数量         帐户     

如上所述,它将是固定的,用户可以提供任意数量的标题名称。

这是我所做的准则:

Grid.Hexgrid = Backbone.Marionette.CompositeView.extend({
         template: "#header", 
         initialize : function (options){
           this.header = options.header;
        },
        onRender : function(){
            ADD THE HEADER INFORMATION HERE WHICH WILL COME UNDER <THEAD></THEAD>
        },

      appendHtml: function(collectionView, itemView, index){
        collectionView.$("tbody").append(itemView.el);
      }
    });

我已在BOLD信中发表了我的意见。有人会帮我完成这个请。

2 个答案:

答案 0 :(得分:1)

您不需要在视图中设置模板属性,因为函数getTemplate会为您执行此操作。

无论如何要以动态方式生成标题我建议您使用其他路线,只需将标题数据传递给您的模板:

serializeData: function() {
    var data = Backbone.Marionette.ItemView.prototype.serializeData.apply(this, arguments);
    data.header = this.header;
    return data;
}

然后在你的模板中你可以做到:

<% _.each(header,function(h){ %>
    <div class="span2"><%= h %></div>
<% }); %>

答案 1 :(得分:0)

使用以下方式完成:

onRender : function() {
            headerInformation = this.header;
            for ( var column in headerInformation) {
                this.$("tr").append("<th>" + headerInformation[column] + "</th>");
            }
        }

最好的问候