I am using Rails and I have a Bootstrap navbar. I need to make it so that depending on which navbar tab you click (Home, OOTD, Account), it will highlight it in some manner (like white text). I tried to dynamically get it to work using active
and even a function which is supposed to toggle it, but it does not work.
My application.html.erb
, which contains my navbar:
<!DOCTYPE html>
<html>
<head>
<title>Finalproj493</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="width: 100%; height: 5vw;">
<ul class="navbar-nav mr-auto nav">
<li class="nav-item">
<a class="nav-link" href="/welcome/index">Home</a>
</li>
<li class="nav-item 1">
<a class="nav-link" href="/ootd">OOTD</a>
</li>
<li class="nav-item 2">
<a class="nav-link" href="/account">Account</a>
</li>
</ul>
</nav>
<br>
<br>
<%= yield %>
</body>
</html>
I was trying to use the is_active()
function to dynamically toggle (the "Rails" way), but it was not working. The function is in my application_helper.rb
, and I added the function call to it in my navbar (shown above):
module ApplicationHelper
def is_active(action)
params[:action] == action ? "active" : nil
end
end
Perhaps I am going about this the wrong way, but can someone suggest a simple way that would incorporate active
navbar styling in Rails?
You can use current_page?
to set the active class. You can create a method in app/helpers/application_helper.rb
:
def active_class(path)
"active" if current_page?(path)
end
and you can use it like this:
<li class="<%= active_class(welcome_index_path) %>">
current_page?
will return true and set the active
class if the current request URI was generated by the path
argument.
You can read more about current_page?
here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.