Switching Present Tab in Rails

Within my application, I have a set of tabs displayed at the top thanks to a general layout in application.html.erb. Here's how they are structured:

<li class="current"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
            <li><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
            <li><%= link_to "Search", provider_search_path %> </li>

My goal is to dynamically switch the selected tab to the "current" state when its respective page is accessed. So if I click on Edit Profile and land on that page, the tabs should now look like this:

<li><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
 <li class="current"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
  <li><%= link_to "Search", provider_search_path %> </li>

I'm interested in achieving this without resorting to adding JavaScript directly to each displayed page. If there's an alternative approach, what would be the best practice for implementing it in the most efficient way possible?

Appreciate any insight.

Answer №1

To determine the current controller and action, you can use the controller.class == and controller.action_name == methods.

Here is an example:

<li class="<%= controller.class == ProviderController and controller.action_name == 'show' ? 'current' : '' %>"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li class="<%= controller.class == StudentController and controller.action_name == 'edit' ? 'current' : '' %>"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li class="<%= controller.class == ProviderController and controller.action_name == 'search' ? 'current' : '' %>"><%= link_to "Search", provider_search_path %> </li>

Although there are other methods to retrieve the current URL of the page, relying on the actions taken within the view ensures accurate styling based on actual user interaction, rather than just the URL in the address bar.

Answer №2

If you want to implement this functionality, consider using the following code snippet:

<li class="<%= controller.controller_path == 'provider' ? 'current' : '' %>"><%= link_to "Home", provider_path(current_user.id), :method=> "GET"%> </li>
<li class="<%= controller.controller_path == 'student' ? 'current' : '' %>"><%= link_to "Edit Profile", edit_student_path(current_user.id) %> </li>
<li class="<%= controller.controller_path == 'search' ? 'current' : '' %>"><%= link_to "Search", provider_search_path %> </li>

Make sure to determine the controller being accessed to control the behavior accordingly.

Answer №3

Check out the tutorial on TabsOnRails

Answer №4

Here's a simple solution:

<%= current_page?(:controller => 'your_controller', :action => 'index') ? 'current' : '' %>

Answer №5

I've created a versatile helper function for handling multiple arguments, making it ideal for nested resources. However, it can also handle a single controller name just like the other solutions.

application-helper.rb:

 def determine_active_state(*links)  
   links.each { |link| return "active" if params[:controller] == link }
 

application.html.erb:

<li class="<%=determine_active_state('home')%>">...</li>

Alternatively,

Here is an example using HAML with nested resources (will be active for any of the provided controller names):

applcation.html.haml:

%li{:class => determine_active_state('blogs', 'comments')}

Answer №6

One possible approach is to pass @current_tab back to the erb from the controller methods when switching pages. This variable can then be used to determine which li element should have the "current" class applied. Another option is to assign a unique attribute or ID to each li element and use your preferred JavaScript framework to dynamically change the classes based on user interaction.

Answer №7

While I can't guarantee that this is the absolute best approach, I'm fearless enough to share my solution with you :)

Here are a few sample menu links extracted from my design:

<li class="nav-calendar"><%= menu_link_to 'teachers', 'show_date', 'Calendar', calendar_url  %></li>
<li class="nav-announcements"><%= menu_link_to 'announcements', nil, 'Announcements', announcements_path %></li>

Next, I devised this handy helper function:

def menu_link_to(*args, &block)
  controller = args.shift
  action = args.shift

  if controller == controller_name && (action.nil? || action == action_name)
    if args.third.nil?
      args.push({:class => 'selected'})
    else
      args.third.merge!({:class => 'selected'})
    end
  end

  link_to *args, &block
end

Answer №8

After some tinkering in the application helper, I managed to get it working smoothly:

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

To implement this, simply use the following code snippet:

<li class="<%= check_current_page(root_path)%>"> <%= link_to "Home", root_path %></li>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Troubleshooting: Navbar dropdown menu in AngularJS gets hidden within UI layout

After spending some time trying to understand why the NavBar drop-down is getting overlapped inside the ui-layout, I realize that I must be overlooking some basic steps. This issue seems so simple, yet it is eluding me. To see the details of the problem, ...

Larger icon graphics

Is it possible to increase the size of Glyphicons in Twitter Bootstrap 3.0 without using the btn-lg class? I found this code that makes glyphicons big: <button type="button" class="btn btn-default btn-lg"> <span class="glyphicon glyphicon-th- ...

Exploring the possibilities of using AngularJS for AJAX functionality in a Ruby On Rails

I recently started learning AngularJS and Rails, and I attempted to develop a Rails application incorporating AngularJS. Currently, I am looking to make a POST request to send data and insert it into the database. In the Activity Controller: def create ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Creating an efficient login system for my website - where do I start?

I've recently started diving into the world of web development, starting with HTML, CSS, and a bit of JavaScript. However, I've hit a roadblock - while I can perform basic styling, I'm struggling to make my projects interactive. My main que ...

Adaptable Bootstrap navigation bar

In the process of creating a responsive menu, I have designed a navbar for desktop that includes 3 text links and 3 small pictures that are also links. However, when transitioning to a smaller screen size, my goal is to keep the 3 small pictures as they a ...

How can a Bootstrap card be designed with the image positioned at the top left, but adjusting based on different

When it comes to Bootstrap 4 cards with images, most have the image positioned at the top using .card-img-top. But what if you want the image to be at the left or at the top depending on the width? Currently, I have two types of cards - one with the image ...

- Prefixing with -webkit-transform and overlooking z-index

When using Safari 5.1.7 on Windows, I noticed that some rotated elements are overlapping others: However, when I test it on Firefox, Chrome, and IE, the issue doesn't occur: Is there a solution to prevent this overlap problem specifically on Safari? ...

JavaScript Reference for the HTML DOM Style's height property and revert back to the initial style height

Hey there! I have a simple fix for those who know JavaScript. I have some code that changes the height style on the first click, but I'm looking for a way to revert back to the original height style on the second click. Here's the code snippet: ...

Trouble with Alignment in Bootstrap 3 Form

I'm currently facing an issue with aligning a form group in Bootstrap 3. My goal is to have them aligned vertically, but I am struggling to achieve this. Any help would be greatly appreciated! Please refer to the screenshot below for reference: Her ...

An error is thrown when using less.js

Every time I attempt to add less.js, I encounter an XmlHttpRequest Exception 101. Including the .less file is done using this method: <link rel="stylesheet/less" type="text/css" href="anything.less" /> This issue only arises when I upload the th ...

Is there a way to incorporate a background image fadeIn effect for ul using CSS3?

I have a list on my webpage where each item is displayed with a CSS3 rotate animation. After the animation finishes, I want to set a background image with a FadeIn effect. To achieve this, I created a "addbg" class for the ul element like so: ul.addbg{ ...

Ensure that the Left and Right menu are fixed in position, while allowing the middle content to be scrollable

I'm in the process of creating a web page with a fixed left and right menu, while the middle content should be scrollable and positioned behind the menus. I've attempted to implement this using the following HTML and CSS, but encountered an error ...

I am encountering challenges and confusion with CSS

I am encountering an issue with my code that is causing some difficulties. The goal is to create a basic div with left, right, and center panes. The left pane loads perfectly, but the right pane, which has the same css styling, displays its children with a ...

What is the best way to ensure that when a div is opened, the information to the right does not get pushed down?

I have a functioning menu bar, but when it expands, the content below is pushed down even though it should not be affected. How can I adjust my code to prevent this issue? View my website here: <div id="menu_wrapper"> <div id="menu"> &l ...

The text exceeds the width of the element

Currently, I am facing an issue with displaying notifications where the text exceeds the element width. I am looking for a solution to make the text wrap to the next line if it is too long. https://i.sstatic.net/5NcNs.png To handle notifications, I am ut ...

The collapsible navbar vanished, where did it go?

While experimenting with the carousel template page, I noticed that the NavBar collapses when the screen width is reduced below a certain pixel size. Initially, everything was working fine as intended. However, after making some modifications to the carou ...

Ensuring that nested objects in an absolutely positioned element do not wrap, clear, or stack

Looking for some assistance with my tooltip menu. The problem I'm facing is that my links keep wrapping to a new line, and I can't figure out how to prevent this. I've already attempted using display:inline and float:left on the links within ...

Step-by-step guide to making a circular "clip-path" work in both Internet Explorer and Firefox

Can someone help me with circle-masking in different browsers? It's working fine on Chrome. I need to make it work on Firefox and IE as well. Looking for a solution without using radius-border... .circle { -webkit-clip-path: circle(100px at 100p ...