Goal
Apply a different class to the nav links to show which page the user is currently on.
Approach
view:
<div>
<%= link_to "Work", work_path, class: active_class(work_path) %>
<%= link_to "About", about_path, class: active_class(about_path) %>
</div>
helper:
def active_class(link_path)
current_page?(link_path ) ? "active" : ""
end
routes:
root 'pages#work'
Outcome
- "active" class IS NOT applied to "Work" link on "/" (FAIL) --> how do I correct this?
- "active" class IS applied to "Work" link on "/work" (SUCCESS)
- "active" class IS applied to "About" link on "/about" (SUCCESS)
CodePudding user response:
May be like this:
def active_class(*paths)
"active" if paths.any? { |path| current_page?(link_path) }
end
You can pass root_path
if you need
<%= link_to "Work", work_path, class: active_class(work_path, root_path) %>
<%= link_to "About", work_path, class: active_class(about_path) %>