Mark html elements with a CSS class

I've got a tab menu with links to different controllers. Depending on
which controllers is the current, I would like the current controller's
tab to have a css class, e.g. class="current". I use the same layout
file for all controllers.

I would like to do kind of the same thing to another menu but this time
depending on which ID is the current. It's a list of posts in the
database, and depending on which post is the current, the current post
shall have a css class in the list of posts.

Does anyone have a simple solutions for this?

hi
in body tag, put a class

then in your menu

  • articles
  • controller
  • ...

    to format this, and highlight the current chosen controller, it would be in css file

    .articles li .articles { highlighted style }

    same for the highlighted posts

Nice solution, but not very flexible. For such things I developed a plugin (site_map) which is hosted on rubyforge. You can install it with:

./script/plugin install svn://rubyforge.org/var/svn/site-map/trunk/site_map``

The basics are:

  1. in routes.rb define your site map:

SiteMap.draw do |map|

map.area 'public do

map.section 'about_us', :controller => 'frontend', :action => 'about_us'
map.section 'signup', :controller => 'account'
map.location :controller => 'frontend'   # not bound to any particular section

end

map.area ‘admin’ do
map.section ‘users’, :controller => ‘/admin/users’
map.section ‘posts’ do
map.location :controller => ‘/admin/posts’
map.location :controller => ‘/admin/comments’

end

end

end

  1. Then in the views there is a current_location helper which returns an object that describes current location. It has all the location attributes (area name, section name, etc) initialized based on current request params (including controller and action names)

You can use any attributes you want (zone / area / section / etc), there is no predefined ones (except you can’t use “location” attribute, because it is reserved keyword).

In your views you can use some helpers like

<%= section_link ‘users’, ‘User management’, :controller => ‘/admin/users’ %>

which is defined in helpers as:

def section_link(section_name, title, url_options)
if current_location.section == section_name

# selected section
link_to title, url_options, :class => 'selected'

else
# normal section
link_to title, url_options
end
end

This saves me from adding new stylesheets if I add new subdivisions to my web applications. It also gives greater flexibility in mapping controllers AND actions to different “locations”. Also, you can render selected e.g. “section” with simple text (not a link). With css solution you can’t do that.

I was thinking a slightly more easier solution. I solved the problem
with the following solution.

<ul>
<% for page in @pages %>
  <li<% if params[:id] == "#{page.id}" %> class="current"<% end %>><%=
link_to page.name, :controller => "pages", :action => "show", :id =>
page %></li>
<% end %>
</ul>