开发者

For the first x in array?

I imagine this has a rather simple answer

<% for user i开发者_如何学Gon @users %>
  <li>
    <%= link_to user.username, user %>
  </li>
<% end %>

Taking my simple example above, how would I apply a class to my <li> to the first three instances returned?

Secondly, how could I just have the the second two items have a different class from the first one? as in 1..2


Either you could count manually (which is kinda ugly):

<% i = 0 %>
<% for user in @users %>
  <li class=<%= (i < 3 ? "foo" : "bar") %>>
    <%= link_to user.username, user %>
  </li>
  <% i = i.next %>
<% end %>

or use each_with_index

<% @users.each_with_index do |user, i| %>
  <li class=<%= (i < 3 ? "foo" : "bar") %>>
    <%= link_to user.username, user %>
  </li>
<% end %>

Once you get to more complex things than i < 3 (like your 1..2 issue) you should think about a helper_method (in helpers) like class_by_position(pos) so that you can write

<li class=<%= class_by_position(i) %>>


The :first-child pseudoselector might be a better way to go, but you'll need to have a counter variable that keeps track of the iterations to do it your way.


Your question is a little vague. I can't tell if you want to stop processing the array after the first x, or not.

If you're just looking to stop after the first x items, or just looking for the 2nd and 3rd items the solution is to use a slice.

Example: just the first 3:

@user[0,3].each do |user|
  ... # only executed for user = @user[0],user = @user[1] and user = @user[3]
end

Example: just the second and third:

@user[1,2].each do |user|
  ... #only only executed for user = @user[1] and user = @user[3]
end

And here's a more specific answer to your question using these new concepts and the content_tag to programatically decide the class of the list item. If you're going to be doing this often, makes a great candidate for a function.

<% first = true %>
<% @user[0,2].each do |user| %>
  <% content_tag :li, 
     :class => first ? "class-for-first-item" : "class-for-2nd-&-3rd" do %>
    <%= link_to user.username, user %>
  <% end %>
  <% first = false %>
<% end %>
<!-- Now to do the rest of them:-->
<% @user[3,-1].each do |user| %>
  <% content_tag :li, :class => "class-for-rest" do %>
    <%= link_to user.username, user %>
  <% end %>
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜