1

I’ve been trying, using Rails/Ember pre-4, to do a fairly typical thing, that is have a page with a navbar and a content section. The navbar only changes on login (shows logout button when logged in and login and register buttons when logged out), not on every page change.

At first thought i could do something in the application.hbs template such as:

{{view navbar}} {{outlet}}

where i set up navbar to respond to login state changes (managed by a state manager). This didn’t seem to work.

Then i tried something like (also in application.hbs):

{{outlet navbar}} {{outlet}}

and tried setting navbar in each route, which results in lots of duplication and also didn’t ultimately work.

Before posting code, wanted to know if anyone already has a good solution to this common situation where certain parts of your page such as a navbar or sidebar only change upon some change in app state, not on every page change.

mmadrid99
  • 155
  • 2
  • 8

1 Answers1

2

There are lots of ways to get this done. The first approach you described is closest to what we are doing. In past ember versions we used view helper for this, today we use {{render}} but it's the same basic concept. For example, application.hbs might look like this:

{{render navbar}} {{outlet}}

Now navbar.hbs can use a simple {{#if}} helper to swap links based on login state.

<div class="navbar">
  <div class="navbar-inner">
    {{#linkTo index class="brand"}}My App{{/linkTo}}
    <ul class="nav">
      <li>{{#linkTo index}}Home{{/linkTo}}</li>
      <li>{{#linkTo about}}About{{/linkTo}}</a></li>
    </ul>
    <ul class="nav pull-right">
     {{#if isAuthenticated}}
     <li><a {{action logout}} href="#">Logout</a></li>
     {{else}}
     <li><a {{action login}} href="#">Login</a></li>
     {{/if}}
    </ul>
  </div>
</div>

Now we add logic to NavbarController that tracks and manages login state.

App.NavbarController = Ember.ArrayController.extend({
  isAuthenticated: false,
  login: function() {
    this.set('isAuthenticated', true);
  },
  logout: function() {
    this.set('isAuthenticated', false);
  }
});

In a real app NavbarController would proxy these requests to another controller, perhaps currentUserController. I've created a working sample here: http://jsbin.com/iyijaf/6/edit

Mike Grassotti
  • 19,040
  • 3
  • 59
  • 57
  • Great, thanks. I extended your example somewhat with a state manager and works as expected http://jsbin.com/exidil/2/edit – mmadrid99 Feb 06 '13 at 20:49
  • 1
    this is a great example. However, I tried to take it a step further and have a conditional in my Index view that uses the same state manager. I asked this as a separate question: http://stackoverflow.com/questions/16267557/ember-statemanager-doesnt-work-after-changing-twice – Ben Apr 28 '13 at 20:38