根据单元格值使用 erb - ruby on rails 为 table 单元格设置不同的颜色
Styling table cell different colors depending on the cell value using erb - ruby on rails
我目前正在 rails 为 ruby 的战舰游戏制作棋盘。
我坚持如何更改 table 单元格的颜色(取决于数组 @actions 中的哪个值在里面。我尝试在 html.erb 中使用 case 语句和 if'statement 但我不能找出正确的语法。还有一件事我想知道:我应该为此做一个辅助方法并在 html 中使用它,而不是在那里编码吗?
这是控制器:
class BoardsController < ApplicationController
def new
@actions = ['none', 'hit', 'miss', 'ship', 'special']
@grid = []
for row in 0..9
@grid.push([])
for column in 0..9
@grid[row].push({
'action' => @actions.sample
})
end
end
end
end
视图如下:
<table class="table table-striped table-bordered">
<% for row in 0..9 %>
<tr>
<% for column in 0..9 %>
<td>
<%= @grid[row][column]['action'] %>
</td>
<% end %>
</tr>
<% end %>
</table>
我认为最简单的解决方案是为每个操作创建 CSS 类,例如:
<style>
.none { background-color: blue; }
.hit { background-color: red; }
.miss { background-color: yellow; }
.ship { background-color: white; }
.special { background-color: green; }
</style>
然后只需在 td
标签的 class
属性中添加操作(即 @grid[row][column]['action']
):
<% for column in 0..9 %>
<td class="<%= @grid[row][column]['action'] %>"></td>
<% end %>
与您的问题无关,但值得注意:您还应该选择使用 each
而不是 for
,这更符合习惯。
例如,您的视图代码可以重构为:
<table class="table table-striped table-bordered">
<% (0..9).each do |row| %>
<tr>
<% (0..9).each do |column| %>
<td class="<%= @grid[row][column]['action'] %>"></td>
<% end %>
</tr>
<% end %>
</table>
我目前正在 rails 为 ruby 的战舰游戏制作棋盘。 我坚持如何更改 table 单元格的颜色(取决于数组 @actions 中的哪个值在里面。我尝试在 html.erb 中使用 case 语句和 if'statement 但我不能找出正确的语法。还有一件事我想知道:我应该为此做一个辅助方法并在 html 中使用它,而不是在那里编码吗?
这是控制器:
class BoardsController < ApplicationController
def new
@actions = ['none', 'hit', 'miss', 'ship', 'special']
@grid = []
for row in 0..9
@grid.push([])
for column in 0..9
@grid[row].push({
'action' => @actions.sample
})
end
end
end
end
视图如下:
<table class="table table-striped table-bordered">
<% for row in 0..9 %>
<tr>
<% for column in 0..9 %>
<td>
<%= @grid[row][column]['action'] %>
</td>
<% end %>
</tr>
<% end %>
</table>
我认为最简单的解决方案是为每个操作创建 CSS 类,例如:
<style>
.none { background-color: blue; }
.hit { background-color: red; }
.miss { background-color: yellow; }
.ship { background-color: white; }
.special { background-color: green; }
</style>
然后只需在 td
标签的 class
属性中添加操作(即 @grid[row][column]['action']
):
<% for column in 0..9 %>
<td class="<%= @grid[row][column]['action'] %>"></td>
<% end %>
与您的问题无关,但值得注意:您还应该选择使用 each
而不是 for
,这更符合习惯。
例如,您的视图代码可以重构为:
<table class="table table-striped table-bordered">
<% (0..9).each do |row| %>
<tr>
<% (0..9).each do |column| %>
<td class="<%= @grid[row][column]['action'] %>"></td>
<% end %>
</tr>
<% end %>
</table>