Dynamic menu ruby on rails and partial

寵の児 提交于 2019-12-06 09:13:37

Add these methods to helpers/appalication_helper.rb

def active_menu?(path, path_right=request.path)
  (URI::parse(path).path == path_right) rescue false
end

def top_menu
  [
    "About",   "../pages/about", 
    "Careers", "../pages/careers", 
    "Contact", "../pages/contact"
  ].each_slice(2).map do |name, path|
    content_tag(:li, link_to(name, path), 
      :class => (active_menu?(path) ? "active_page" : ""))
  end.join('').html_safe
end

Now in your view:

.three.columns
  %ul#nav
    = top_menu

Note:

Use route helpers for path instead of hard coding them. Assuming you have a controller called PagesController, you can rewrite the top_menu method as follows:

def top_menu
  [
    "About",   about_pages_path, 
    "Careers", careers_pages_path, 
    "Contact", contact_pages_path
  ].each_slice(2).map do |name, path|
    content_tag(:li, link_to(name, path), 
      :class => (active_menu?(path) ? "active_page" : ""))
  end.join('').html_safe
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!