Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(@business)}'

which isn't very DRY.

I was wondering if anyone knows a good way to modify the link_to helper itself to automatically add an 'active' class to all links to the current page.

If it helps, I'm open to using HAML or SLIM.

like image 234
Dylan Karr Avatar asked Sep 05 '13 16:09

Dylan Karr


4 Answers

I wrote simple helper method using build in view helper current_page? when you can specify custom class name in html_options hash.

def active_link_to(name = nil, options = nil, html_options = nil, &block)
  active_class = html_options[:active] || "active"
  html_options.delete(:active)
  html_options[:class] = "#{html_options[:class]} #{active_class}" if current_page?(options)
  link_to(name, options, html_options, &block)
end

Examples (when you are on root_path route):

<%= active_link_to "Main", root_path %>
# <a href="/" class="active">Main</a>

<%= active_link_to "Main", root_path, class: "bordered" %>
# <a href="/" class="bordered active">Main</a>

<%= active_link_to "Main", root_path, class: "bordered", active: "disabled" %>
# <a href="/" class="bordered disabled">Main</a>
like image 63
cintrzyk Avatar answered Sep 23 '22 20:09

cintrzyk


It's a solved problem, just use active_link_to gem. Your example simplifies to this:

= active_link_to t('.profile'), business_path(@business)
like image 43
Grocery Avatar answered Sep 22 '22 20:09

Grocery


I faced same requirement and here is my solution.

Create a method within ApplicationHelper

def active_class(link_path)
    current_page?(link_path) ? "active" : ""
end

And inside your view:

    <li class="<%= active_class('/') %>">
      <%= link_to 'HOME', root_path %>
    </li>
like image 42
egyamado Avatar answered Sep 23 '22 20:09

egyamado


This is a good case for writing your own helper that wraps the link_to. In your application_helper.rb you can write a method active_link_to that takes the same params as link_to + current_page, and then just calls link_to like you are doing above.

like image 37
steakchaser Avatar answered Sep 23 '22 20:09

steakchaser