Conditional Navbar

How to display different navbars on specific pages

This one is easier than you think. You may have noticed, but in Rails, the params gives you the controller and action that you're currently in. Try it out. Throw a raise in your controller, then refresh the browser.

# app/controllers/pages_controller.rb
def home
  raise
end
Raise error

Now you'll notice if you look below the source code, Rails lists out our parameters which appear to be empty. But when where look inside of the params in the console, it's giving us a hash with information we can use.

Params controller action

Inside of that hash, we have acess to both the controller and the action.

The Solution

Now go to your application.html.erb file and let's build a conditional statement based on these two values.

1. Removing navbar on landing page
# app/view/layouts/application.html.erb
# ...
<body>
  <% unless params[:controller] == 'pages' && params[:action] == 'home' %>
    <%= render 'shared/navbar' %>
  <% end %>
  <%= yield %>
  ...
2. Display a different navbar for a signed in user (w/Devise)
# app/view/layouts/application.html.erb
# ...
<body>
  <% if user_signed_in? %>
    <%= render 'shared/user_navbar' %>
  <% else  %>
    <%= render 'shared/default_navbar' %>
  <% end %>
  <%= yield %>
  ...