-1

I have a blog section in my rails app and was wondering what a good way to handle assigning the CSS class active would be, based on the page that would be open.

Should this be done via .erb with if and do statements? It would need to reflect the category the post is in.

Blog Category Table:

create_table "blog_categories", force: :cascade do |t|
  t.string "name"
  t.integer "parent_id"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

Posts Table Column: t.integer "category_id" - This is stored to relate to the .id of the cat.

My categories are represented with a parent_id of NULL and subcategories are those with a parent_id set to the .id of the main category.

Jake
  • 1,086
  • 12
  • 38
  • 1
    You can take reference from this: https://stackoverflow.com/questions/9879169/how-to-get-twitter-bootstrap-navigation-to-show-active-link – Kartikey Tanna May 30 '18 at 12:23

2 Answers2

2

You can do this by defining a function in your application_helper.rb

def active_class(path)
 "active" if current_page?(path)
end

current_page? method will return active if the user is on the same url as passed in path parameter. checkout its documentation.

Then in view you can use it like this.

<li class="<%= active_class new_user_session_path %>">
Talha Junaid
  • 904
  • 1
  • 7
  • 15
  • Is this better than including the code directly such as: `<%= 'active' if current_page?(root_path) %>`? – Jake May 30 '18 at 12:51
  • 1
    Both are same logically, but defining a function is better in a sense it makes your code reusable and clean. – Talha Junaid May 30 '18 at 13:02
0

i prefer you to use these helpers below one is for single path eg:

<li class="<%= active_class(first_path) %>">

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

this one is for multiple array of links eg

<li class="<%= active_class_multiple([first_path, second_path]) %>">

# pass array of paths to get current page active link
def active_class_multiple(array)
  array.include?(request.path) ? 'active' : ''
end