0

我的每个循环都有问题。打印 programdetail.name 和 programdetail.bodypart 的行不打印值。你也知道我怎样才能让这个循环更有效率吗?我想打印“奇数”类的前 2 个项目和非类的其他 2 个项目。如此等等。

<% @counter = 0 %>
<% @program.programdetails.each do |programdetail| %>
    <% @counter = @counter + 1 %>
    <% @counter = @counter % 3 %>
    <% if (@counter == 0)
      @counter -= 1
    end %>
    <%= '<h3 class="odd"><span class="moduleLabel"> #{programdetail.name}</span><span class="moduleDescription">#{programdetail.bodypart}</span></h3>' if @counter != 0 %>
    <%= '<h3><span class="moduleLabel">#{programdetail.name}</span><span class="moduleDescription">#{programdetail.bodypart}</span></h3>' if @counter != 0 %>

<% end %>
4

1 回答 1

3

cycle如果您想要奇数/偶数组合或集合,helper 可能会起作用:

<% @program.programdetails.each do |programdetail| %>

  <h3 class="<%= cycle("odd", "odd", "", "") %>
    <span class="moduleLabel"><%= programdetail.name %></span>
    <span class="moduleDescription"><%= programdetail.bodypart %></span>
  </h3>

<% end %>

要修复您的代码:

<% @counter = 0 %>
<% @program.programdetails.each do |programdetail| %>
  <% @counter = (@counter % 4) + 1 %>
  <h3 class="<%= ((1..2).cover?(@counter))? 'odd': '' %>">    
    <span class="moduleLabel"><%= programdetail.name %></span>
    <span class="moduleDescription"><%= programdetail.bodypart %></span>
  </h3>
<% end %>
于 2013-05-16T21:17:05.033 回答