问题描述
我正在尝试制作一个如下所示的html表:
I'm trying to make an html table that looks like this:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
我的数据结构是这样的:@f_ary = [1..250]
My data structure is like this: @f_ary = [ 1..250]
这是我的haml代码:
Here's my haml code:
%table{:border => "1"}
%tbody
%tr
- cnt = 0
- @f_ary.each do |f|
- cnt += 1
%td= cnt
- if cnt == 5
- cnt = 0
%tr
我当前的输出如下:
<table border='1'>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<tr></tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</tbody>
</table>
我希望它看起来像这样:
I want it to look like this:
<table border='1'>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
</tr>
</tbody>
</table>
推荐答案
您应该尝试将用于创建行和列数组的所有逻辑放在控制器中.这样,在Haml中渲染视图就变得非常简单:
You should try to put all the logic for creating the rows and columns array in your controller. Rendering the view in Haml then becomes very simple:
控制器:
@items = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15]
]
查看:
%table
%tbody
- @items.each do |row|
%tr
- row.each do |column|
%td= column
如果您有一个扁平的项目数组,而不是像我的示例中那样的数组数组,则可以使用flat_array.each_slice(5).to_a
轻松地将其转换,其中5
是列数.
If you have a flat array of items rather than an array of arrays as in my example, you can easily convert it with flat_array.each_slice(5).to_a
, where 5
is the number of columns.
这篇关于如何使用循环和haml与ruby创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!