Search code examples
ruby-on-railsrubyerbhelpermethods

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?


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>