简体   繁体   中英

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?

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 eg

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM