Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 / Bootstrap 3: how to display a different navigation bar on different pages?

Here is the _header.html.erb of our Rails 4 app, made with Bootstrap 3 components:

<header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <nav>
      <div class="col-xs-4">
        <%= link_to "APP NAME", root_path, id: "logo" %>
      </div>
      <div class="col-xs-4 text-center">
        <ul class="nav navbar-nav navbar-center">
          <li><%= link_to "Features",   features_path %></li>
          <li><%= link_to "Pricing",   pricing_path %></li>
          <li><%= link_to "Blog", '#' %></li>
        </ul>
      </div>
      <div class="col-xs-4">
        <ul class="nav navbar-nav navbar-right">
          <% if current_user.try(:admin?) %>
            <li><%= link_to "Users", users_path %></li>
          <% end %>
          <% if logged_in? %>
            <li><%= link_to "Dashboard", current_user %></li>
            <li><%= link_to "Settings", current_user %></li>
            <li><%= link_to "Log out", logout_path, method: "delete" %></li>
        <% else %>
          <li><%= link_to "Log in", login_path %></li>
          <li><%= link_to "Sign up", signup_path %></li>
        <% end %>
        </ul>
      </div>
    </nav>
  </div>
</header>

As you can see, this conditionally displays a navigation bar, depending on whether the current user is logged out, logged in or logged in as admin.

However, we are wondering how we could display a different navigation bar on different pages.

For instance, on all public pages (home, features, pricing, blog, help, etc.), we would like to display the Features, Pricing & Blog links (whether the user is logged in or not) but on the inner pages of the app (dashboard, settings, etc) we would like to remove these links.

EDIT: to make things clearer, what we call the public pages are actually our static_pages, which rely on our StaticPages#Controller, while the inner app pages such as dashboard and settings rely on our Users#Controller.

How can we achieve this? Do we need to create a new _header.html.erb partial?

Is there a particular Rails way to do that?

like image 767
Thibaud Clement Avatar asked Dec 11 '22 22:12

Thibaud Clement


1 Answers

You could put each variation of the navbar in it's own partial and make use of content_for.

In your application layout you could have logic that checks if a specific navbar should be rendered, like this:

<% if content_for?(:navbar) %>
    <%= yield(:navbar) %>
<% else %>
   # code for default navbar
<% end %>

And inside your views, where you want the different navbars

 <% content_for :navbar do %>
      <%= render 'nav_bar_variation_one' %>
 <% end %>

and

 <% content_for :navbar do %>
      <%= render 'nav_bar_variation_two' %>
 <% end %>
like image 188
user1063998 Avatar answered Jan 11 '23 01:01

user1063998