Search code examples
javascriptruby-on-railsbackbone.jscoffeescriptmarionette

Choose between two templates render with Marionette


I use Marionette (Backbone.js) on my Rails app.

What i want to do is load another template if matches an id, this is what i have

join_room.html.slim file

...
MyAppManager.start({
      tmpltRoute: templateRoute
});
...

menu_view.js.coffee

@MyAppManager.module "Layout", (Layout, MyAppManager, Backbone, Marionette, $, _) ->
  Layout.MenuView = Marionette.ItemView.extend
    initialize: (options)->
      @isPremium = options.isPremium
      @isStandard = options.isStandard
      @tmpltRoute = options.tmpltRoute
    template: JST[this.tmpltRoute]

Solution

  • You can override getTemplate on your ItemView to achieve this (see docs)

    https://marionettejs.com/docs/v2.4.0/marionette.view.html#change-which-template-is-rendered-for-a-view

    getTemplate: function(){
        if (this.model.get("foo")){
          return JST[foo];
        } else {
          return JST[bar];
        }
    }