开发者

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>


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. :)


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜