Rails 3 - Referencing the URL to determine if a Nav Item is class="selected"
The app can have the following URLs:
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
There is always access to params hash, so you can check params[:controller] or params[:action] anywhere in your views. There is always request.env['PATH_INFO'], where the complete URL is stored as well.
As for the breadcrumb referenced in the second part of the question, I believe there is no general way of doing it. There is no solid background behind the relations between views. Site logic is basically constructed across the views, so there is no solid way of determining it.
Since you always have Files underneath Project in this particular view, where is the problem? Can't you just highlight project if Files are selected?
Edit:
Implementation really depends on your design and if you need direct hints, you would have to paste a gist/paste link to your code. In general the idea is as follows:
<% if params[:controller] == :files
<% b1class = "active" %>
<% b2class = "active" %>
<% b3class = "active" %>
<% else %>
....
<% end %>
<div class=breadcrumb>
<p class=<%= b1class> Project </p>
<p class=<%= b2class> Photos </p>
<p class=<%= b3class> Files </p>
</div>
If I understand you correctly, wouldn't you want to be using: current_page?(your_page_path)
Check out this article: A Better Way to Add a ‘selected’ Class to Links in Rails
It's a pretty robust nav_link
helper that addresses multiple scenarios in which a 'selected' class needs to be added. The url_segment
option should help you out.
To do this I just compare the request path with the resource path. In this case I have an active record class called 'page' which holds the basic pages such as home and about. Then I created a partial view for each link called pages/_links.html.erb:
<% if current_page?(page) %>
<li class="active"><%= link_to "#{page.name}".html_safe, page.url.empty? ? page : page.url %></li>
<% else %>
<li><%= link_to "#{page.name}".html_safe, page.url.empty? ? page : page.url %></li>
<% end %>
You can call that partial with something similar to:
<%= render :partial => "pages/links", :collection => @display_pages, :as => :page %>
精彩评论