Rails 3 - Referencing the URL to determine if a Nav Item is class=“selected”

The app can have the following URLs:

<li> /projects/ </li> <li> /projects/3 </li> <li> /projects/3/photos </li> <li> /projects/3/photos/312 </li>

I'd like to know how in Rails 3 I can look at the current URL and know which of the lines above is currently active, so I can add a class="selected"

Additional exmaple..

If the user's browser is on: /projects

And the Nav looks like

Projects   - Photos   - Files

Projects is Active

but if the user's browser is on: /files

Projects is active

and Files is active (they both apply).

Ideas? thanks

I use this method:

Give each li an id (i.e. app_nav_li_projects, app_nav_li_files)

Set @li_to_select in your controller or controller method to the li id you want to select

Use JQuery on the page to add the selected class to the li id of the @li_to_select

My JQuery looks like this:

Note that your JQuery has to be in the page so the @li_to_select is inserted correctly.

Joshua Martin wrote:

I use this method:

Give each li an id (i.e. app_nav_li_projects, app_nav_li_files)

Set @li_to_select in your controller or controller method to the li id you want to select

Use JQuery on the page to add the selected class to the li id of the @li_to_select

My JQuery looks like this:

<script type="text/javascript">

// Adds the current class to the requested app nav menu $(document).ready(function(){ $("li#<%= @li_to_select%>").addClass("selected"); });

</script>

Terrible. As I've said numerous times on this forum, dynamic JS -- and inline JS even more so -- are problematic from a design standpoint and should always be avoided. What you should be doing here is using an external JS file to which you pass the ID by a method such as having it look in the DOM.

But I'm not sure this is the right approach. Rails provides a bunch of helpers such as current_page? and link_to_if_current_page, so it seems to me that you should be able to do this on the server side.

[...]

Joshua S. Martin

Best,

Thanks all. I have no intention of wanting to do this client-side with JS... Only Server Side... Any suggestions? Seems like this is something every RAils app needs solved?

Please quote when replying.

nobosh wrote:

Thanks all. I have no intention of wanting to do this client-side with JS... Only Server Side... Any suggestions? Seems like this is something every RAils app needs solved?

Yes. Read my previous post, where I explained how to do it server-side.

Best,