Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top