Ran
Ran

Reputation: 3523

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?

Upvotes: 1

Views: 572

Answers (2)

Max Williams
Max Williams

Reputation: 32943

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>

Upvotes: 4

LuckyLuke
LuckyLuke

Reputation: 49077

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>

Upvotes: 4

Related Questions