1

I want to add a class to one of the elements in a Handlebar template while initialising the view.

Here is the where I initialise the LayoutView

export default LayoutView.extend({
  className: 'LandingPageHeaderDetail',
  template: fs.readFileSync(`${__dirname}/LandingPageHeaderDetail.hbs`, 'utf8'),
  initialize: function (options) {
     this.setMenu(options)    
   },
   setMenu (options) {
    // in here I want to add a className to one of the elements 
    // in the template file
   // for example template = <ul><li id="id1">dkjfls</li><li id="id2">kdjfkls</li>
   // if (options == id1) { add class x to element} else { add class to y element }
   }

My question is how do I navigate the template tree, find the element I'm looking for and add a class to it.

I've tried using jQuery selectors as follows: $('#id1') but it returns null, probably because the template hasn't rendered yet. Any ideas?

Linda Keating
  • 2,215
  • 7
  • 31
  • 63

2 Answers2

1

You can use Marionette's serializeData function.

initialize: function(options){
    this.myOptions = options;
},
serializeData: function(){
    return {id: this.myOptions};
}

Then you can create a helper for Handlebars using the answer from this question: Handlebars.js if block helper ==

Then in your template, put the actual logic to apply the class:

<ul>
    <li id="id1" {{#if_eq id "id1"}}class="classname"{{/if_eq}}>dkjfls</li>
    <li id="id2" {{#if_eq id "id2"}}class="classname"{{/if_eq}}>kdjfkls</li>
</ul>
Community
  • 1
  • 1
J. Titus
  • 9,535
  • 1
  • 32
  • 45
0

As you said, you can't work with the template inside initialize function cause the template is not rendered yet. Use Render event, it's triggered after the view has been rendered.

Marionette.View.extend({
  onRender: function(){
    // manipulate the `el` here. it's already
    // been rendered, and is full of the view's
    // HTML, ready to go.
    this.setMenu();

  },
  setMenu: function(){
    // now i can manipulate the template...
  }
});

Other solution would be to use serializeModel or templateContext.

Velja Matic
  • 560
  • 4
  • 15