ruby “first” helper method?

i have the following file member.html.erb:

<ul class="members-list">
  <%@members.each do |member|%>
  <li class="member-item">
    <%=member.name%>
  </li>
  <%end%>
</ul>

i want to add the "first" class to the first li that will be generated (just to the first), so it would look like this:

<ul>
  <li class="member-item first">john</li>
  <li class="member-item">chris</li>
</ul>

any thoughts?

Answers


You could acheive this using CSS aswell if its purely for the styling. If you either has a ID or class on the ul then you could in CSS write

ul.member-list li:first-child {
WHATEVER STYLING CODE THAT YOU WOULD PUT IN member-item first
}

and for the rest of the li-tags

ul.member-list li {

}

If you want the class to be added you could e.g

<ul>
    <% @members.each_with_index do |member, i| %>

    <% if i == 0 %>
        <li class="member-item first">
            <% member.name %>
        </li>
    <% else %>
        <li class="member-item">
            <% member.name %>
        </li>
    <% end %>
</ul>

Similar, but more terse, approach to Andreas/Heikki's answer:

<ul>
  <% @members.each_with_index do |member, i| %>
    <li class="member-item<%= ' first' if i == 0 %>">
        <% member.name %>
    </li>
  <% end %>
</ul>

Need Your Help

Why brackets are necessary in catch block in java?

java syntax braces catch-block

In java if we have to execute only one statement after if or for the brackets are not necessary. We can write:

How can I display XML with whitespace formatting?

php xml formatting simplexml whitespace

I have a web page that builds an XML from an existing XML applying changes. I want to output the new XML file in a textarea as a preview. It displays any nodes that were present in the original XML

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.