开发者

link helpers, current_pages and navigation

I'm trying keep a tab on a page to be selected by checking the controller. I.e., any page that displays the Products controller shoul开发者_JAVA百科d keep the Product tab selected. I can't seem to find the right approach. I was considering of making a helper method, but it seems a bit tricky to put the helper into my link_to helper. Here is my guess of how I can make it work:

<%= link_to "Products", products_path, current_controller?('products') ? :class => 'selected' %>

Anyone has a better idea?


And the problem wont just be in one place, you'll have many tabs and each tabs will have rules on which controllers+action combinations it would be active/selected for.

It's a common problems and some people have written "plugins" for the same too.

I suggest you write helpers. Make your own mini DSL. Decide for yourself what is easy and nice to look at:

<%= link_to_tab_for("Products", products_path, :controller => "sss", :action => "", :other_html_options => {})

Next step, implement this method in helpers/application.rb

def link_to_tab_for(name, path, options)
  controller = options.delete(:controller)
  action = options.delete(:controller)
  klass = [].push(options[:class]).compact
  if current_controller?(controller) && (action ? current_action?(action) : true)
    klass.push("selected")
  end
  options[:class] = klass.empty ? "" : klass.join(" ")
  link_to(name, path, options)
end

Have a gander at attempting the above method to your liking of course.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜