watts
watts

Reputation: 95

Multiple Layouts in Ember.js?

Coming from a Rails background, you can have multiple Layouts - for say, anonymous user pages and then authenticated pages.

Is this possible with Ember?

I've tried declaring a new templateName in my UsersRouter, with no avail.

I've also checked this guide: http://emberjs.com/guides/views/adding-layouts-to-views/

But it doesn't seem to be working :/

Upvotes: 4

Views: 2646

Answers (1)

Darshan Sawardekar
Darshan Sawardekar

Reputation: 5075

You can use {{render}} inside an if helper to show different layouts.

For instance if you have an ApplicationController that has login and logout action handlers, and a corresponding `loggedIn' property.

App.ApplicationController = Ember.Controller.extend({
  loggedIn: false,

  login: function() {
    this.set('loggedIn', true);
  },

  logout: function() {
    this.set('loggedIn', false);
  }
});

The you can bind to the loggedIn property inside the application template like so.

<script type='text/x-handlebars' data-template-name='application'>
<button {{action login }}>Login</button>
<button {{action logout }}>Logout</button>

{{#if loggedIn}}
  {{render 'user'}}
{{else}}
  {{render 'guest'}}
{{/if}}

</script>

Where user and guest are corresponding templates.

<script type='text/x-handlebars' data-template-name='user'>
<h1>User layout</h1>
<div class='box user'>
{{outlet}}
</div>
</script>

<script type='text/x-handlebars' data-template-name='guest'>
<h1>Guest layout</h1>
<div class='box guest'>
{{outlet}}
</div>
</script>

Here's a working jsbin.

Edit: To not use the application route based on some static criteria or loaded via model hooks, you can override the renderTemplate method of the ApplicationRoute.

App.ApplicationRoute = Ember.Route.extend({
  renderTemplate: function() {
    var loggedIn = false;
    if (loggedIn) {
      this.render('user');
    } else {
      this.render('guest');
    }
  }
});

Upvotes: 6

Related Questions