I'm generating a bunch of links in a menu bar on my app. When the user is viewing one of the pages of the menu bar I'd like the style to change to show that they are viewing the present page. It's a pretty straightforward task that I've got working.
What I'd like to do is dry up my helpers. I'm building the links like so:
link_to('events', :controller => 'event_sections', :action => 'show', :group_id => @group), :class => "current_page_item"
I'm repeating myself a lot with the 'if is current page' code. I was wondering if there was a good way to first build all the links I need and then add the :class => "cu开发者_如何学Crrent_page_item" to it.
link_to
takes URL options and HTML options. You can just put them in their own hash
link_to('events', :controller => 'event_sections', :action => 'show', :group_id => @group), :class => "current_page_item"
Becomes:
link_to'events', {:controller => 'event_sections', :action => 'show', :group_id => @group}, :class => "current_page_item"
Notice the new { } around the controller path.
It depends on how complex your 'if current page' logic is, I suppose. I normally create a simple helper such as this to use the controller name and the link text to decide if the link is 'current':
def tab(name, link)
css_class = (controller.controller_name.humanize =~ /#{name}/i ? "current_page_item" : "page_item")
link_to name, link, :class => css_class
end
Then you can call this instead of link_to where you're creating your tabs:
= tab "Events", :controller => 'event_sections', :action => 'show', :group_id => @group
I would approach it in a different way: what about setting a variable like @current_page_name in your controller (each action would set it) and then all your link_tos would check that variable before adding the class.
Then, to dry it up even more, you could create a partial or a function that would wrap around your link_to (and I see that idlefingers just posted a similar answer).
精彩评论