0
votes

I'm new to MarionetteJS and love it. I've created an ItemView and CompositeView to show the values within a collection. This is great, but I want to render custom field/column headers. I've done this using Backbone.Collection and using _.each(item.keys(), function(key){... I cannot does this with MarionetteJS since I am using an ItemView for each Row.

I've tried using appendHTML, but am having difficulty accessing the collection. Here's what I got so far:

...
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);
},
...

This is not working. Any help would be appreciated.

1

1 Answers

0
votes

You can store extra data in this compositeView and then use it in template. Allow me to use CoffeeScript below.

Step 1: Get the data and store it in a context variable say this.headers

initialize: ->
  @headers = @collection.last().attributes.keys

Step 2: Make the data available in template using built-in templateHelpers

templateHelpers ->
  view = @ # Use this line because context will change below
  headers: ->
    view.headers

Step 3: Show it in template with simple iteration. I'll use Handlerbars for example

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