How do I give Marionette templates data attributes?

Ziggy picture Ziggy · Jul 5, 2013 · Viewed 9.2k times · Source

Here I am at the beginning of a project. I am using zurb-foundation and marionette. I have an element that is rendering a template that is supposed to be tabs. As it stands:

define([
  "backbone",
  "marionette"
], function(Backbone, Marionette) {

  MyItem = Backbone.Marionette.ItemView.extend({
    template: "#design-tabs",
    className: "section-container tabs",

    onRender: function() {
      $(this.el).foundation();
    }
  });

  return MyItem;
});

there are no tabs. I think this is because the <div> being rendered to replace the <script> tag in the template does not have a particular data attribute (data-section). I went looking for something like 'className' that I could add to the ItemView declaration above in order to include data-attributes, but I have come up dry. I want something like:

MyItem = Backbone.Marionette.ItemView.extend({
  template: "#design-tabs",
  data: {
    data-section: "",
    data-foo: "bar"
  },
  className: "section-container tabs",
  .
  .
  .

How do I add data attributes to the <div> (or otherwise) that replaces the <script> in a template?

Answer

David Sulc picture David Sulc · Jul 5, 2013

To add data properties, use Backbone's attributes hash:

var MyView = Backbone.Marionette.ItemView.extend({
  template: "#design-tabs",
  className: "section-container tabs",
  attributes: {
    "data-section": "",
    "data-foo": "bar"
  }
});

Documentation: http://backbonejs.org/#View-attributes