Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i conditionally style a <li> in rails?

I have a rails app using a ul as a toolbar. I want to have a style (selected) to apply to the page the user is on.

How can I do that?

This is what I have so far, but the selected style is hard coded and I'm also not sure how to know what page is selected.

      <ul>
        <li class="firstItem"><%= link_to "About", '/about' %></li>
        <li class="item"><%= link_to "Page1", '/page1' %></li>
        <li class="item selected" <%= link_to "Page2", '/page2' %></li>
        <li class="item"><%= link_to "Contact", '/contact' %></li>
        <li class="lastItem"><%= link_to "Blog", '/blog' %></li>
      </ul>
like image 522
NotDan Avatar asked Feb 21 '10 18:02

NotDan


3 Answers

I agree totally with Jarrod's advice, but just in case you encounter the need to process additional conditions (and want to avoid ugly embedded ruby in your HTML code), take a look at Rails' content_tag method.

With it, you can replace something like:

<li class=<%= @post.active? ? 'active' : 'suspended' %>>
  <%= link_to @post.name, post_path(@post) %>
</li>

With something like:

<%= content_tag :li, link_to(@post.name, post_path(@post), :class => @post.active? ? 'active' : 'suspended' %>

And of course, sticking this code into a helper and calling it from there will earn you more elegance-points.

Hope this helps.

PS: This is my first post on Stackoverflow, please be gentle. :)

like image 71
nicosuria Avatar answered Nov 07 '22 00:11

nicosuria


if each li is linked to different controller you can use controller_name to add or not the selected class

Here is an example from my app, it's in haml

  %ul
    %li
      %a{:href => '/kebabs', :class => ('current' if controller_name == 'kebabs')} Admin kebabs
    %li
      %a{:href => '/statistics', :class => ('current' if controller_name == 'statistics')} Statistiques
    %li
      %a{:href => '/people', :class => ('current' if controller_name == 'people')} Admin Personnes

cheers

like image 5
denisjacquemin Avatar answered Nov 07 '22 01:11

denisjacquemin


You can also use css for this. Give each the body each page a class and id from your controller and action names.

<body class="<%= controller.controller_name %>" id="<%= controller.action_name %>">

Then give your ul and li elements an id.

<ul id="nav'>
  <li id="about"></li>
  <li id="contact"></li>
  <li id="blog"></li>
</ul>

Now you can reference a specific link on a specific page from your stylesheet.

body.blog#index ul#nav a#blog:link

So if you want to make section links 'sticky' you can reference them all at once, leaving out the body id.

body.blog ul#nav a#blog:link,
body.contact ul#nav a#contact:link {
  background-color: red;
}

Check out more on CSS selectors.

like image 1
Jarrod Avatar answered Nov 07 '22 00:11

Jarrod