In my view I have:
在我看来,我有:
<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 %>
Is there DRYer way of accomplishing this (as the only change I make is adding the class 'active' for the first photo) i.e. can I put the first item within the loop and detect the first iteration?
是否有DRYer完成此任务的方式(因为我做的唯一更改是为第一张照片添加“活动”类),即我可以将第一项置于循环中并检测第一次迭代吗?
2 个解决方案
#1
12
Try 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 %>
#2
1
['apple', 'orange', 'pear'].each_with_index do |fruit, index|
p "first is #{fruit}" if index == 0
p fruit
end
#1
12
Try 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 %>
#2
1
['apple', 'orange', 'pear'].each_with_index do |fruit, index|
p "first is #{fruit}" if index == 0
p fruit
end