Rails - select the current menu item

I made a little helper that adds class="selected". First of all, he uses current_page?to investigate whether the current path is the current menu item and 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. Choice /admin/catalogsworks like a charm. But there are no subpages ( /admin/catalogs/1etc.)

I think my approach may be corrupted by current_page?method limitations

Do you have any ideas on how I should improve this script to accept similar URLs, or is there a smarter way to achieve it?

+3
source share
4 answers

, , , controller_name action_name, , / . , URL, .

search_page_active = controller.controller_name == 'students' && \
                     controller.action_name == 'search'
+3

:

def current_link_to label, path
  link_to label, path, class: (current_page?(path) ? "active" : nil)
end
+5

In my case, I have a lot of namespaced controllers, so I like to show that the current view is also in the Menu Path, I used Michael van Rooijen's solution, and then I customize it for my case.

Assistant

def cp(path)
  "current" if request.url.include?(path)
end

View

<%= link_to "All Posts", posts_path, class: cp(posts_path) %>

Now, if my menu bar / users and my current page is / users / 10 / post, also the link / users are set with the "current" class

+2
source

You can use link_to_unless_current.

0
source

Source: https://habr.com/ru/post/1729629/


All Articles