Alistair Laing
Alistair Laing

Reputation: 973

Conditionally wrapping elements in haml

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

Upvotes: 1

Views: 394

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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.

Upvotes: 1

Related Questions