如何在Ruby on Rails循环中向每个其他元素添加左右类? [英] How do I add left and right classes to every other element in a loop in Ruby on Rails?
问题描述
我正在Ruby on Rails应用程序中工作.我有一个循环可以像这样创建div:
I am working within a Ruby on Rails app. I have a loop that creates divs like this:
<% @snorks.each do |snork| -%>
<div>
<%= snork %>
</div>
<% end %>
我需要输出使每个其他div像这样向左或向右浮动:
And I need the output to have every other div be floated left or right like this:
<div class="left">
Allstar Seaworthy
</div>
<div class="right">
Casey Kelp
</div>
<div class="left">
Dimmy Finster
</div>
<div class="right">
Daffney Gillfin
</div>
<div class="left">
Tooter Shellby
</div>
<div class="right">
Dr. / Uncle Galeo
</div>
此外,我需要添加一个div,每两个div分别为class="clear"
,
Additionally, I need to add a div with class="clear"
every two divs, like this:
<div class="left">
Allstar Seaworthy
</div>
<div class="right">
Casey Kelp
</div>
<div class="clear"></div>
<div class="left">
Dimmy Finster
</div>
<div class="right">
Daffney Gillfin
</div>
<div class="clear"></div>
<div class="left">
Tooter Shellby
</div>
<div class="right">
Dr. / Uncle Galeo
</div>
<div class="clear"></div>
我进行了研究,发现了很少
I have researched, and found a few posts saying that the alternate classes can be accomplished easily by using cycle()
, and that does work. However, when I use it in two places within the loop it stops working right and just outputs something like this:
<div class="left">
Allstar Seaworthy
</div>
<div class="left">
Casey Kelp
</div>
<div class="left">
Dimmy Finster
</div>
<div class="left">
Daffney Gillfin
</div>
<div class="left">
Tooter Shellby
</div>
<div class="left">
Dr. / Uncle Galeo
</div>
Ruby on Rails在循环中替换类并每隔一个循环添加一些东西的最佳做法是什么?
推荐答案
根据文档,如果您需要嵌套的,请给它们命名.否则,它们都将共用默认"名称,并且会冲突.
According to the documentation, if you need nested ones you name them. Otherwise they will both share the name "default" and conflict.
<% @snorks.each do |snork| -%>
<div class="<%= cycle('left', 'right') -%>">
<%= snork %>
</div>
<%= cycle('','<div class="clear"></div>', :name=>"cleardiv") %>
<% end %>
这篇关于如何在Ruby on Rails循环中向每个其他元素添加左右类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!