Search code examples
ruby-on-railsruby-on-rails-4erbpartial

In Rails 4, how can I change the text in the nav bar based on the current page?


I am working on a Rails 4 project where I would like a different link to appear on the navigation bar depending on the current page. This is how I am trying to set it up:

<ul>
  <% if current_page?("/company") %>
    <li>Company Space</li>
  <% elsif current_page?("/user_page") %>
    <li>User Space</li>
  <% else %>
  <% end %>
</ul>

I know I've written this part correctly, because when I put it in the application.html.erb layout page, it works just fine. When I put the same exact thing in the top nav bar, however, it doesn't work. The nav bar is in a partial called _header.html.erb which is currently rendered in the layout as follows:

<body>
  <%= javascript_include_tag "application" %>

  <%= render 'layouts/header' %>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <%= yield %>
  <%= render 'layouts/footer' %>
</body>

I assume this has something to do with the nav bar not detecting the current page. I am hoping someone can tell me why this is happening, and ideally I would like to find a relatively DRY solution that would allow me to have this feature. (I have thought of creating separate partials for the different conditions, and then putting the logic for displaying the partial in application.html.erb, but given that this is far from the only content in the nav bar, the maintainability of that seems quite dismal.)

Thanks for any help!


Solution

  • To expand upon nathan's answer, specify action

    <% if params[:action] == 'company' %>
        <li>Company Space</li>
    <% else params[:action] == 'user_page' %>
        <li>User Space</li>
    <% end %>
    

    This will work... but it doesn't feel like the cleanest way. Perhaps go about doing it with JS for it to be cleaner?