You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中如何根据in_groups_of分组的数组项索引设置样式类?

解决方案:基于位置为Rails数组分组元素设置类

嘿,这个需求其实很好解决~关键是要先明确你要基于哪种「位置」来设置类——是分组后子数组里的相对位置,还是原数组里的全局索引?我把两种场景的实现都给你写出来:

场景1:基于分组后子数组内的相对位置

如果你想给每一行的第一列元素加专属类,第二列加另一个类(比如区分左右列样式),可以在遍历分组后的子数组时用each_with_index拿到元素在子组内的位置(0或1),再做条件判断:

<% @entitiquestions.in_groups_of(2, false) do |group| %>
  <tr>
    <% group.each_with_index do |entitiquestion, idx_in_group| %>
      <!-- 这里根据子组内位置设置类,比如第一列加col-left,第二列加col-right -->
      <td class="<%= idx_in_group == 0 ? 'col-left' : 'col-right' %>">
        <span data-tooltip class="hint--bottom hint--info" data-hint="<%= entitiquestion.question.query %>">
          <!-- 这里放置你的元素内容,比如问题文本、操作按钮等 -->
        </span>
      </td>
    <% end %>
  </tr>
<% end %>

这里的idx_in_group只会是0或1(因为你用了in_groups_of(2)),你可以完全根据自己的样式需求替换类名,比如first-column/second-column。

场景2:基于原数组的全局索引

如果你需要根据元素在原@entitiquestions数组里的原始位置设置类(比如偶数索引加浅色背景,奇数索引加深色背景),可以先把元素和它的全局索引绑定,再进行分组:

<% # 先把每个元素和原数组索引配对,再执行分组逻辑 %>
<% @entitiquestions.each_with_index.map { |item, idx| [item, idx] }.in_groups_of(2, false) do |group_with_indices| %>
  <tr>
    <% group_with_indices.each do |entitiquestion, global_idx| %>
      <!-- 根据全局索引的奇偶设置类,你可以换成任意自定义条件逻辑 -->
      <td class="<%= global_idx.even? ? 'even-item' : 'odd-item' %>">
        <span data-tooltip class="hint--bottom hint--info" data-hint="<%= entitiquestion.question.query %>">
          <!-- 元素内容 -->
        </span>
      </td>
    <% end %>
  </tr>
<% end %>

这种方式下,global_idx就是元素在原数组里的原始位置(从0开始计数),你可以拓展出更复杂的判断逻辑,比如global_idx >= 5 ? 'highlight-item' : 'regular-item'。

内容的提问来源于stack exchange,提问作者Jerome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:58:11