Add an 'active' class to all active links in rails?

后端 未结 7 724
醉酒成梦
醉酒成梦 2021-02-05 15:08

Basically, I have a lot of code that looks like this:

link_to t(\'.profile\'), business_path(@business), class: \'#{\'active\' if current_page? business_path(@bu         


        
7条回答
  •  眼角桃花
    2021-02-05 15:47

    Here's the helper I use. I add an optional "match_text" parameter for added flexibility (for instance, if I want to mark a link as active when the actual request path is a child page of the link's destination.)

    def link_to_active(text, destination, options = {})
      match_text = options.delete(:match_text)
    
      classes = options[:class].present? ? options[:class].split(" ") : []
      classes << "active" if request.fullpath.downcase == destination.downcase || (match_text && request.fullpath.downcase.include?(match_text.downcase))
    
      options = options.except(:class)
      options.merge!(:class => classes.join(" ")) unless classes.empty?
    
      link_to(text, destination, options)
    end
    

提交回复
热议问题