How to change the class of a menu item in Rails

I have a layout with menu navigation. I am using a template that I found on the internet. There is an HTML page for each menu item, and the class of the li element is called "selected" for each respective page. It looks like this:

  <nav>
    <ul class="sf-menu" id="nav">
      <li class="selected"><%= link_to "home", root_path %></li>
      <li><%= link_to "about me", about_path %></li>
      <li><%= link_to "my portfolio" %>
        <ul style="z-index: 2;">
          <li style="z-index: 2;"><%= link_to "portfolio one", portfolio_one_path %></li>
          <li style="z-index: 2;"><%= link_to "portfolio two", portfolio_two_path %></li>
          <li style="z-index: 2;"><%= link_to "portfolio three", portfolio_three_path %></li>
        </ul>
      </li>
      <li><%= link_to "blog", blog_path %></li>
      <li><%= link_to "contact", contact_path %></li>
    </ul>
  </nav>

      

So this is in my file application.html.erb

. My question is, how do I programmatically change each class of the li element to "selected" depending on which link the user clicks on? Can this be done with Ruby or do I need to use JavaScript?

+3


source to share


3 answers


I think you need a helper method current_page?

- http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-current_page-3F



<li class="<%= "selected" if current_page?(root_path) %>"><%= link_to "home", root_path %></li>
...

      

+1


source


I think you want to do something like:

<%= link_to "portfolio one", portfolio_one_path,  class: current_page?(products_path) ? "selected" : "not_selected" %>

      



for your links

0


source


Controller and action names are available for your views in the params hash. So, if they are different actions / controllers, you can do something like below:

<li class=<%= "selected" if params[:controller] == 'portfolio' && params[:action] == 'action_name' %>><%= link_to "portfolio one", portfolio_one_path %></li>

      

I personally am not a big fan of this approach and I stick to it in my ideas directly. I usually inject logic into my helpers and use them.

0


source







All Articles