How do I give Marionette templates data attributes?
Asked Answered
A

2

13

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?

Asare answered 5/7, 2013 at 0:50 Comment(1)
For now I am just going to make a meaningless <div> to hold the whole thing, so that the data-attribute will appear in the DOM as required. However, my question is not "how do I make my thing work?", rather it is "how do I put data-attributes in the <div> that replaces the <script> that contains or is a marionette template?".Asare
A
40

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

Arzola answered 5/7, 2013 at 9:10 Comment(2)
Winner! Yeah, using marionette without ever having done backbone by itself, I have a hard time knowing which docs I should check. I didn't even look at the backbone docs. sad faceAsare
The event aggregator is from Marionette, not Backbone. If you're looking for a good introduction to Marionette views, take a look a the free sample to my book: samples.leanpub.com/marionette-gentle-introduction-sample.pdf You can also check out the source code at github.com/davidsulc/marionette-gentle-introductionArzola
M
14

If you prefer or need dynamic values, you can do in this way:

attributes: function() {
  return {
    'src': this.model.get('avatar_src')
  };
}
Morphophoneme answered 21/8, 2014 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.