1

I have a rails app that uses haml for its templates. In one of my haml partial:

- customer.each_with_index do |customer, index|

  -# start a new row for every odd defendant
  - if index % 2 > 0
    .grid-row

  -# for each customer output each their details
    .column-half
      .bold-normal
        = t('.customer')
        = index + 1
      =# other info

  -# if the customer in the first column is the last one then add a blank column-half
  - if index + 1 == customers.size && index % 2 > 0
    .column-half
       

I would like it to produce some html as follows:

<div class="grid-row">
  <div class="column-half">
    Customer 1
  </div>
  <div class="column-half">
    Customer 2
  </div>
</div>
<div class="grid-row">
  <div class="column-half">
    Customer 3
  </div>
  <div class="column-half">
    &nbsp;
  </div>
</div>

Ideally I would like to keep the customers details section as DRY as possible.

Many thanks

Alistair Laing
  • 983
  • 1
  • 7
  • 18

1 Answers1

1

The easiest way, I think, is to split them in chunks of two, and not bother with any of the conditional modulo stuff.

- customers.each_slice(2) do |left, right|

  .grid-row
    .column-half
      .bold-normal
        = left # or whatever

    .column-half
      - if right
        .bold-normal
          = right # or whatever
      - else
        &nbsp;

You can also extract the customer details section (.column-half) into a partial.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • I like your suggestion (haven't attempted it yet) however I need to know what number that customer is using the index. its not a hard coded number it basically a variable number of customers who have bought a specific product. – Alistair Laing Dec 03 '15 at 09:04
  • @AlistairLaing: "a variable number of customers who have bought a specific product" - this looks like important data and not an ephemeral list index. As such, it should be available somewhere in the object being rendered. – Sergio Tulentsev Dec 03 '15 at 09:06
  • Ah yes looks think this post http://stackoverflow.com/questions/5983977/ruby-array-each-slice-with-index answers that question – Alistair Laing Dec 03 '15 at 09:06
  • I need to be able to keep the left/right side DRY because they would be identical – Alistair Laing Dec 03 '15 at 09:10
  • @AlistairLaing: partial. – Sergio Tulentsev Dec 03 '15 at 09:11