首页 > 解决方案 > 使用嵌入式 Ruby 迭代器时如何交替使用 HTML 表格行类?

问题描述

下面我有一个index.html.erb带有 HTML 表的文件的一部分,我的目标是在使用 Ruby 迭代器时交替使用白色和灰色行。我希望奇数行拥有<tr class="bg-white">& 偶数行拥有<tr class="bg-gray-50">. 我正在使用 TailwindCSS 并且我已经为孩子们尝试了奇偶变换类,但我认为这不是答案。我真的不明白如何将其表达为 if 语句。我不能做“如果客户 ID 是奇数或偶数:是白色或灰色”,因为如果删除了一个客户,我不希望顶部/下方有两个白色或两个灰色行(例如,如果客户端 ID 26 被删除我现在有 25 和 27 次触摸)。非常感谢您提前提出任何建议。

      <tbody>
        <% @clients.each do |client| %>
          <tr class="bg-white">
            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 ">
              <%= client.first_name + " " + client.last_name %>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
              <%= client.phone_number %>
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
            </td>
            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
            </td>
          </tr>
        <% end %>
      </tbody>

标签: rubyerbtailwind-css

解决方案


您可以cycle为此使用视图助手:

  <tbody>
    <% @clients.each do |client| %>
      <%= tag.tr(class: cycle("bg-white", "bg-gray-50")) do %>
        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 ">
          # ...
        </td>
      <% end %>
    <% end %>
  </tbody>

推荐阅读