Best way to highlight current page in Rails 3? — apply a css class to links conditionally

后端 未结 8 1769
野趣味
野趣味 2020-12-04 14:25

For the following code:

<%= link_to \"Some Page\", some_path %>

How do I apply a css class current using the

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 15:04

    I tried to combine a couple of the mentioned techniques with my own needs.

    def current_page(path)
      'current' if current_page?(path)
    end
    
    def create_nav_link(string, path, method)
      link_to string, path, data: { hover: string }, method: method
    end
    
    def create_nav_item(string, path, method = nil)
      content_tag :li, create_nav_link(string, path, method), class: current_page(path)
    end
    

    Basically it allows you to use it like this: create_nav_item("profile", profile_path) which will result in:

  • Profile
  • ,

    or

  • Profile
  • if this is the current page.

    I didn't use request.url.include?(path) since it will also always highlight the "Home" button, and I couldn't think of a work around by far.

提交回复
热议问题