开发者

Why HAML (in Ruby of Rails) cannot optionally output a <tr> and just output a <td>?

开发者 https://www.devze.com 2023-02-26 00:38 出处:网络
The following code is to output a 2-column table -- to output <tr> only every 2 items; otherwise, just a <开发者_如何学编程td>, but I found out the output has <tr> all the time, for

The following code is to output a 2-column table -- to output <tr> only every 2 items; otherwise, just a <开发者_如何学编程td>, but I found out the output has <tr> all the time, for every <td>, why is that -- is it a bug?

- arr = [2, 4, 6, 8, 10, 12]
%table
  - arr.each_with_index do |num, i|
    - if i % 2 == 0
      %tr
        %td= "column 1: #{num}"
    - else
      %td= "column 2: #{num}"


You can also use each_slice instead of each_with_index. each_slice(2) breaks the original array into 3 groups of 2 arrays so it easier to iterate over using haml. A touch less code too.

- arr = [2, 4, 6, 8, 10, 12]

%table
  - arr.each_slice(2).each do |row|
    %tr
      %td= "column 1: #{row[0]}"
      %td= "column 2: #{row[1]}"


Actually, if you write it like this:

- arr = [2, 4, 6, 8, 10, 12]
%table
  - arr.each_with_index do |num, i|
    - if i % 2 == 0
      %tr
        %td= "ODD row #{i}/#{i % 2} - column 1: #{num}"
    - else
      %td= "EVEN row #{i}/#{i % 2} - column 2: #{num}"

You will see the code is executed correctly. But, HAML automatically closes the <TR> tag (the closing comes automatically with the indentation). And likewise, HAML automatically adds the forgotten <TR> tag for the dangling <TD>.

So one possible way to solve that:

- arr = [2, 4, 6, 8, 10, 12]
%table
  - arr.each_with_index do |num, i|
    - if i % 2 == 0
      %tr
        %td= "column 1: #{num}"
        %td
          -if arr.size > i+1
            = "column 2: #{arr[i+1]}"

Hope this helps.

[EDIT: added erb example]

In erb you can do it a bit nicer (but i generally do not like to use it):

<% arr = [2, 4, 6, 8, 10, 12] %>
<table>
  <%= arr.each_with_index do |num, i| %>
    <% if i % 2 == 0 %>
      <tr><td><%= "column 1: #{num}" %></td>
    <% else %>
      <td><%= "column 2: #{num}" %></td></tr>
    <% end %>
  <% end %>
</table>
0

精彩评论

暂无评论...
验证码 换一张
取 消