问题描述
下面我有一个带有 HTML 表的 index.html.erb
文件的一部分,我的目标是在使用 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>
解决方法
您可以使用 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>
,
在我看来,使用 Tailwind CSS even
和 odd
变体对于您想要实现的目标来说是一个很好且干净的解决方案。
这是使用 Ruby .erb
<table class="w-full">
<tbody>
<tr class="even:bg-gray-100 odd:bg-blue-100">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">smith</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">555 111-1111</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>
<tr class="even:bg-gray-100 odd:bg-blue-100">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">johns</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">555 222-2222</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>
<tr class="even:bg-gray-100 odd:bg-blue-100">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">davison</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">555- 333-3333</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>
</tbody>
</table>
这是一个实现示例: https://play.tailwindcss.com/2BNYhQIwfQ
记得在变体部分添加 'even','odd'
。
variants: {
backgroundColor: ['odd','even'],},