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

 ̄綄美尐妖づ 提交于 2019-12-02 20:28:06

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.

You can use the each_slice like so:

- @f_ary.each_slice(5) do |row|
  %tr
    - row.each do |cnt|
      td=cnt

update

This could be the most un-ruby way of doing it, (I did this around 3 years back). So

check out above answers & they are much more better

I will just keep this answer without deletion, just as a reference on, how NOT to do it... ;)


Have an internal counter in the view, when it comes to 5, add a . psudo will look some thing like this

couneter = 0 

@items.each |item|
   if counter == 0
    <tr>
   end
   if counter != 5
     <td>item</td>
     counter ++
   end
   if counetr == 5
     </tr>
     counetr = 0
   end 

end


end

I hope u get the idea

cheers

sameera

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!