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

In app/helpers/application_helper.rb

def cp(path)
  "current" if current_page?(path)
end

In your views:

<%= link_to "All Posts", posts_path, class: cp(posts_path) %>

Basically write a simple wrapper around it. Additionally you could extend the method to allow additional classes to be applied by adding arguments. Keeps the views concise/dry. Or, without extending the method, you could just do simple String interpolation like so to add additional classes:

<%= link_to "All Posts", posts_path, class: "#{cp(posts_path)} additional_class" %>

Leave a Comment

tech