Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I create a table using loops and haml with ruby?

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

My data structure is like this: @f_ary = [ 1..250]

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 

My current output looks 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>

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>
like image 588
sybind Avatar asked Apr 02 '11 07:04

sybind


2 Answers

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:

Controller:

@items = [
  [1,  2,  3,  4,  5],
  [6,  7,  8,  9,  10],
  [11, 12, 13, 14, 15]
]

View:

%table
  %tbody
    - @items.each do |row|
      %tr
        - row.each do |column|
          %td= column

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.

like image 154
Todd Yandell Avatar answered Nov 05 '22 23:11

Todd Yandell


You can use the each_slice like so:

- @f_ary.each_slice(5) do |row|
  %tr
    - row.each do |cnt|
      td=cnt
like image 35
James Brennan Avatar answered Nov 05 '22 22:11

James Brennan