in the bootstrap navigation bar. You can get the effect of a button being clicked by adding the class active
. Naturally, I want to use this on my pages. For example if I'm on the about us page I want the about us button clicked.
What is the best way to go about this? I was going to go to each page and at the bottom have a jQuery function add the class active
to it. Is there a better way?
For anyone having trouble making sense of this, here is an example with my paths and filenames laid out explicitly. As a pretty new person to rails, I was having trouble figuring it out. Thanks to the other people who answered above, as it helped me figure it out!
I placed the Bootstrap navbar in my application.html.erb file:
This goes in the application_helper.rb file:
That's it! Now your application will dynamically add the 'active' class to whatever page is currently being viewed (i.e. it's corresponding list item in the navbar). This is much simpler (and more DRY) than adding the navbar manually to each page (view) and then updating the 'active' class.
Please try this in each page, check the cotroller or action and add the css
For example:
You may define a helper method in
application_helper.rb
Now you can use like:
create_link 'xyz', any_path
which would render as<li class="active"><a href="/any">xyz</a></li>
Perfect for bootstrap navigation!
in my opinion, a cleaner way to achieve that is to write a
link_to_in_li
method in application_helper.rb:then use it this way
I find the code inside
li
a little difficult to read.Read about
current_page?
hereYou can add a method for handle logic with
current_page?
, example a method :example bootstrap navbar template
So, on view looks like
HTML
HAML
Or you can use
request.fullpath
to get current full of path if a current path have a parameterexample
and on your
application_helper.rb
read about request.fullpath here
Why limit yourself to only
li
elements? And why not support multiple class names along withactive
? This solution lets me:link_to
(e.g. add an icon inside the link)application_helper.rb
active
to the whole class name of the link element instead of it being the sole class.So, add this to
application_helper.rb
:And on your template you can have something like this:
You can also specify or not a
class_name
and use it like this:Thanks to previous answers 1, 2 and resources.