Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally closing a tag in HAML

Tags:

haml

I'm iterating through a set of items and displaying them in lists nested in divs. The goal is to have a div for each day and within each div show the items for that day.

How do I do this in HAML? I don't think I can (or should) conditionally close and create a new tag like I could in erb.

I tried:

- @items.each do |item|
  - if item date is diff from previous make a new container
    .container
      %h2 #{item.date}
      = yield_content :display_item item
  - else
    = yield_content :display_item item

But this creates the following:

<div class="container">
<h2>01/28/2012</h2>
      <ul>
            <li>
              ... item
        </li>
      </ul>
</div>
        <li>
        ...item
      </li>

But I want the other item in the same div. I'm using ruby, sinatra (including the content_for helper)

like image 351
aar Avatar asked Dec 21 '22 02:12

aar


1 Answers

The answer is to use more and better Ruby :)

- @items.group_by(&:date).each do |date,items|
  .container
    %h2= date
    - items.each do |item|
      = yield_content :display_item item

See Enumerable#group_by docs for more details.

You could close and re-open the containers and headers as you were thinking, but this is a horrible, hard-to-maintain hack that I would suggest against. Embrace the elegance of Ruby and Haml; don't write Haml like it was ERB.

like image 90
Phrogz Avatar answered Apr 20 '23 03:04

Phrogz