如何检测视图中的第一次迭代? (导轨4)

时间:2014-02-18 09:59:17

标签: ruby-on-rails ruby-on-rails-4 erb

在我看来,我有:

 <div class="item active">
   <%= image_tag "2.jpg",size: "500x300", class: "no-resize" %> 
   <div class="carousel-caption">
     Some tag.
   </div>
 </div>
 <% @photos.each do |photo|%>
 <div class="item">
   <%= image_tag photo.attachment.url,size: "500x300",class: "no-resize" %> 
   <div class="carousel-caption">
     Some tag.
   </div>
 </div>
<% end %>

是否有DRYer实现此目的的方式(因为我做的唯一更改是为第一张照片添加“活动”类),即我可以将第一项置于循环中并检测第一次迭代吗?

2 个答案:

答案 0 :(得分:12)

尝试each_with_index

<% @photos.each_with_index do |photo, i |%>
 <div class="item <%= "active" if i.zero? %>">
   <%= image_tag photo.attachment.url,size: "500x300",class: "no-resize" %> 
   <div class="carousel-caption">
    Some tag.
   </div>
 </div>
<% end %>

答案 1 :(得分:1)

['apple', 'orange', 'pear'].each_with_index do |fruit, index|
  p "first is #{fruit}" if index == 0
  p fruit
end