views:

39

answers:

2

I have made a small helper that adds class="selected". Primarily it uses current_page? to investigate if the present path is the current menu item, and the select it.

module MenuHelper
  #renders menu items and emphasizes current menu item
  def topmenu
    pages = {
      "products" => admin_products_path,
      "categories" => admin_categories_path,
      "catalogs" => admin_catalogs_path,
      "sales channels" => admin_sales_channels_path
    }
    pages.map do |key, value|
      classnames = %( class="current") if current_page?(value)
      "<li#{classnames}>#{link_to(key, value)}</li>"
    end
  end
end

And in /layouts/application.html.erb:

<ul class="topmenu">
<%= topmenu %>
</ul>

There is a big flaw in my approach. Selecting /admin/catalogs works like a charm. But any subpages do not (/admin/catalogs/1, etc.)

I think that my approach may be flawed by the limitations of the current_page? method

do you have any ideas on how I should either enhance this script to accept similar urls, or is there a smarter way to achieve it?

+1  A: 

The way I built a similar menu helper was to look at the controller_name and action_name attributes and then decide if a given page is selected/active or not. That's less specific than the full URL, so might be useful.

search_page_active = controller.controller_name == 'students' && \
                     controller.action_name == 'search'
calmh
This approach works fine, thanks! I made a slight change in my method and now it works. I had to replace `if current_page?(value)` with: `if controller.controller_name == key`
Jesper Rønn-Jensen
A: 

You could use link_to_unless_current.

Mick Sharpe
I decided not to use `link_to_unless_current` because it's a different functionality. I *do* want a link to the menu item `catalogs_path` especially when looking on a sub page like catalog_path(@current_catalog).Also, it's using the same method: `current_page?`. So it does not really help me
Jesper Rønn-Jensen