views:

17

answers:

2

I have a dynamic submenu that is rendered according to which page the user is on. I placed the following code in a _sub_menu.html.erb partial:

<a href="/dashboard/index" class="current">Index</a>
<a href="/dashboard/account">Account</a>
<a href="/dashboard/payments">Payments</a>`

From my my main view, I call <%= render 'sub_menu' %>, which works.

However, I want to change the class="current" part according to which page the user is on. I was hoping to do this from the render by passing in a local parameter and rendering according to that, but it seems hacky:

<%= render 'sub_menu' , :locals => {:active_item => 'payments'} %>

Plus the logic becomes really ugly. Is there a better way of doing this?

A: 

I think you can make use of the block parameter to link_to_unless_current, which provides the content to render when the link is the current page:

<%= link_to_unless_current("Index", :action => 'index') { link_to("Index", :action => 'index', :class => 'current' } %>
<%= link_to_unless_current("Account", :action => 'account') { link_to("Index", :action => 'account', :class => 'current' } %>
<%= link_to_unless_current("Payments", :action => 'payments') { link_to("Payments", :action => 'payments', :class => 'current' } %>

Does that work?

Chris
A: 

You can define an additional helper method, that would be calling link_to_unless_current:

def link_to_current_with_class(name, current_class, options = {}, html_options = {}, &block)
  link_to_unless_current(name, options, html_options) do
    options[:class] = current_class + " " + options[:class]
    link_to(name, options, html_options)
  end
end

and then call it from you navigation partial:

<%= link_to_current_with_class "Index", "current", "/dashboard/index" %>
Matt