Oleksiy Kachynskyy
Oleksiy Kachynskyy

Reputation: 683

Multiple layouts in Ember 2

I need implement next application structure with 3 routes:

localhost/users
localhost/posts
localhost/settings

'users' and 'posts' routes should have basic layout1 with main navbar. 'settings' route should have another layout2 with second navbar.

How can I implement multiple layouts approach with Ember > 2.12?

Can I set a layout name/path for each route or group of routes?

Upvotes: 0

Views: 168

Answers (1)

Michael Boselowitz
Michael Boselowitz

Reputation: 3006

I can think of two possible recommended approaches to this problem. I've used both in different scenarios. You can either:

  1. Use a component to encapsulate each navbar and then present them accordingly in each template
  2. Set the templateName attribute of each route to use the correct template.

The component approach seems to be the easiest/most used in my experience. It also allows you to have differences within your base route template. e.g.:

users.hbs:

{{layout1}}
<h1>Users<h1>
...

posts.hbs:

{{layout1}}
<h1>Posts</h1>
...

While if you use the templateName approach, you are locked into using the same exact template. So, if you need any customization between any page that uses the same layout, you must use a subroute. e.g.:

routes/users.js:

import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});

routes/posts.js:

import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});

templates/layout1.hbs:

<nav>...</nav>
{{outlet}}

A third possible approach, though I don't necessarily recommend it, is to dynamically replace the navbars in the application.hbs template. The application controller/template have access to a special attribute called currentPath, which you can used to create two computed properties (isLayout1 and isLayout2).

With that, this becomes a viable, though like I said, not necessarily recommended solution:

application.hbs:

{{#if isLayout1}}
    <nav>layout 1</nav>
{{else}}
    <nav>layout 2</nav>
{{/if}}
{{outlet}}

Upvotes: 1

Related Questions