I am currently building an app that has a tabbed interface. To my surprise I realized that I have never had to code a tabbed application before. I wanted an easy way to add tabs to my rails application. I used a helper method to identify what the currently selected tab is and add an active class to it.
def link_with_active(text, url) link = link_to text, url if request.request_uri == url return '<li class="active">' + link + '</li>' else return '<li>' + link + '</li>' end end
Basically this method is an if statement that adds the active class to the li item. Since I would almost always build a tabbed list with an li I thought it was a safe assumption to build this in to the method. Then I just call the helper method from my view. Like so.
<ul> <%= link_with_active "Home", "/" %> <%= link_with_active "New Invoice", new_invoice_path %> </ul>
To be honest I am not totally sure if this is the best way to do this. If anyone has a better way of doing so please comment.
Hi Stewart,
I just ran into the same problem. I try to write a helper that will generate a simple list of actions. Did you find a better solution to this problem?
Thank you in advance! Regards,
David
HI David,
Funny you ask this now because I was working on a better solution the other day. My thoughts now are to use javascript to do this and take it away from the server side. So if your using jquery it might look something like this.
if(window.location.pathname == l.url)
$(l).addClass(“active”);
This code will not work but you can use window.location.pathname to get the current url of the page and then apply any extra css classes you want.