Martin C
Martin C

Reputation: 23

Backbone/Marionette - handling multiple layouts for one region

I have two main page layouts: one is the default layout that is going to be used for most pages and the other one is a bare layout without the header/footer etc. that will be used for example for the login page. There might be more in the future.

My current router:

var AppRouter = Backbone.Router.extend({
    routes: {
        'login': 'login',
        'main': 'main'
    },

    login: function(){
        var mainLayoutView = new MainLayoutView({
            'layout': 'bare'
        });
        App.Notes.mainLayoutContainer.show(mainLayoutView);
    },

    main: function(){
        var mainLayoutView = new MainLayoutView({
            'layout': 'default'
        });
        App.Notes.mainLayoutContainer.show(mainLayoutView);
    }
});

How should approach the implementation of the MainLayoutView to be able to render the layout specified in options? Or should I actually have two separate layouts to handle the two templates? They'll obviously share a lot of functionality, though, so I'd rather have only one.

Upvotes: 0

Views: 334

Answers (2)

Martin C
Martin C

Reputation: 23

I think I've found the best way to handle this. I've decided to set the template dynamically in "initialize":

var MainLayoutView = Backbone.Marionette.LayoutView.extend({
    initialize: function(options){
        if(options.layout==='bare'){
            this.template = '#bare-layout';
        }
        else{
            this.template = '#default-layout';
        }
    }
});

This way I can use as many templates for a layout as I want to. Although I'm starting to think that ideally I should be using separate instances of LayoutView for that.

Upvotes: 0

lcoderre
lcoderre

Reputation: 1303

One way could look like this...

MainLayoutView = Backbone.Marionette.ItemView.extend({
  initialize: function(options){
    this.layout = options.layout;
  },

  onRender: function() {
    if (this.layout == 'default') { // or "fullView"
      // Render all components
    } else {
      ...
      // Perhaps there's nothing here
    }
    // Render the center partial view
  }
});

Another way could be directly in your view template. Marionette suggests to have a templating system (Handlebars, Jade, ...).

If you don't use a templating system, first you should consider using one. Second, if you thought about always rendering all the views and simply $(element).hide() what you don't want: DON'T. The advanced users will be able to make the elements visible again and perhaps abuse of your system. Plus, this is useless processing and useless data sent through the wire :-)

Upvotes: 1

Related Questions