cssruby-on-railsviewlink-toview-helpers

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.


Solution

  • 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.