0

It's a problem after using the solution here Best way to add "current" class to nav in Rails 3

def nav_link(link_text, link_path)
  class_name = current_page?(link_path) ? 'current' : ''
  content_tag(:li, :class => class_name) do
    link_to link_text, link_path
  end
end

For example, I have localhost/action1, and localhost/action2, each with a nav button. It works great when user is in either page. In this situation, one of the button would have a 'current' css class.

But, if I set root_path to one of them, let's say is the /action1, so when user visit localhost, the button for action1 won't have a current class

How can I solve add the missing current css class when setting it as the root_path?

Community
  • 1
  • 1
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • Hm, why so difficult comparison? Maybe it would be easier to compare the request.path to link path (if you use built-in methods to get path for link)? – Alex Jan 01 '15 at 17:29

2 Answers2

2

You can query the router itself to give you the controller and the action for the current path and just compare it to the current values from params.

def nav_link(text, path)
  recognized = Rails.application.routes.recognize_path(path)

  klass = "current" if recognized[:controller] == params[:controller] &&
    recognized[:action] == params[:action]

  content_tag(:li, class: klass) do
    link_to(text, path)
  end
end
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52
  • Is it possible to recognize queries like `localhost/posts?number=7`. Possiblely `recognized[:number]`? – ZK Zhao Jan 02 '15 at 04:19
  • @cqcn1991 `localhost/posts?number=7` and `localhost/posts` are identical as far as the router is concerned. If you want to take the query parameters into account, you need to fetch and switch on them yourself (`request.query_parameters` gives you `{"number"=>"7"}`). – Jiří Pospíšil Jan 02 '15 at 10:07
1

You may wish to highlight your nav menu the following way - I am pretty sure this works irrespective setting the root path:

<ul>
  <li class="<%= "current" if params[:controller] == "home" %>">Home</li>
  <li class="<%= "current" if params[:controller] == "action1" %>">Action 1</li>
  <li class="<%= "current" if params[:controller] == "action2" %>">Action 2</li>
</ul>

You may wish to replace

params[:controller]

with

params[:action] 

depending on the level you wish to highlight. I have used this setup in a recent project and it worked for me. Good luck !

ChloeMaster
  • 119
  • 2