Rails menu link style depending on current page
I have a simple navigation menu with plain html links that target different pages. All of these pages share this menu, which is separated out in a partial.
I would like to have the current page's lin开发者_Go百科k be highlighted in bold. A generic version of my (non-working) implementation looks like this:
# 'pagetwo' view
<%= render :partial => "shared/nav" %>
# partial
<%= link_to "Home", home_url, :id => "home" %>
<%= link_to "Page 1", pageone_url, :id => "pageone" %>
<%= link_to "Page 2", pagetwo_url, :id => "pagetwo" %>
Do I solve this with JavaScript?
The link_to_unless_current
suggestion appears to be working. Does anyone know how to assign different CSS class to each outcome using this method?
Unless you need to change the boldness of the links between page requests (i.e. in response to client side events), you might look into using the block form of link_to_unless_current or, for a more general solution, look into current_page?
Another option might be adding classes to the body (or similar container element) based on your current page and then writing CSS rules to target links in specific contexts. For example:
body.home a#home_link { font-weight: bold }
body.about a#about_link { font-weight: bold }
Here is the solution I found, which is the most compact I have yet seen. It builds on the answer given by @thatothermitch (thank you and +1!).
I used link_to_unless_current
for all the links, i.e.
# partial
<div id="manage_list"> # already surrounds the entire partial
<%= link_to_unless_current "Home", home_url, :id => "home" %>
<%= link_to_unless_current "Page 1", pageone_url, :id => "pageone" %>
<%= link_to_unless_current "Page 2", pagetwo_url, :id => "pagetwo" %>
</div>
I then added CSS styles that pick up on whether the <a>
tag exists:
#manage_list p{ font-weight:bold; }
#manage_list p a{ font-weight:normal; }
This way, there is no need to pass any variables, write any javascript, or add any helper.
I hope this is helpful for any others who are experiencing the same problem. :)
You can do this a simple helper
In application helper put this
def set_selected(url_hash)
current_page?(url_hash) ? "current" : ""
end
Your links will call the helper to set the class name
<%= link_to "Home", home_url, :id => "home", :class => set_selected({:controller => 'homes', :action => 'index'}) %>
<%= link_to "Page 1", pageone_url, :id => "pageone", :class => set_selected({:controller => 'page_ones', :action => 'index'}) %>
CSS definition for the current
class goes in the application.css or any other css file in your application
.current{
font-weight:bold;
}
精彩评论