Let's say you're building a sweet navigation in your Rails application and the design you're implementing shows that you've got different states that have different visual cues.
Those states might be inactive, hovering and active or current. Inactive and hovering seems pretty straight forward, you can do all that in CSS.
.Nav-Item { // Styles for the "inactive" nav item state // would go here.}.Nav-Item:hover { // Styles for the "hover" nav item state // would go here.}
But the active or nav item state that indicates you're currently on the same page as an item in the nav isn't a simple CSS solution. To solve this, you'll need to use a built-in Rails helper calledcurrent_page?
.
With thecurrent_page?
helper you can pass it things like a relative or absolute path that you'd like to check or you can even pass it actions and controllers with parameters for it to check. Doing so will return either atrue
orfalse
.
How this could look in your mark up is this,
<%= link_to({ controller: 'page', action: 'about' }, { class: "Nav-Item #{'is-current-page' if current_page?(controller: 'page', action: 'about')}" }) do %> About Us<% end %>
I'm using thecurrent_page?
helper inside alink_to
helper block. Specifically it is being passed to the class attribute where it is saying, if the current pagecurrent_page?
is the same as the page handled by theabout
action in thepage
controller, then add the value ofis-current-page
to the class attribute.
Now I could have this in my CSS,
.Nav-Item { // Styles for the "inactive" nav item state // would go here.}.Nav-Item:hover { // Styles for the "hover" nav item state // would go here.}.Nav-Item.is-current-page { // Styles for the nav item that corresponds // with the current page the user is viewing}
Now we're able to handle inactive, hovering and current page states in a Rails application nav.
Originallyposted on michaelsoolee.com.
Thanks for taking the time to read this article! I'd love to stay in contact and send you tips on programming and design and making side projects through my newsletter.Click here to sign up.
Top comments(1)

- Email
- LocationBirmingham, United Kingdom
- WorkSenior Developer
- Joined
This is handy, thank you!
For further actions, you may consider blocking this person and/orreporting abuse