Haml is beautiful

Haml is a templating engine of sorts for Ruby on Rails, but it’s also so much more than that. The documentation can tell you pretty much everything you need to know, but you have to see to believe. Let’s take a simple snippet of code from my 1st ed. Agile Web Development With Rails:

<table cellpadding="5" cellspacing="0">
<% for product in @products %>
  <tr valign="top">
 
    <td>
      <img src="<%= product.image_url %>"/>
    </td>
 
    <td width="450">
      <h3><%=h product.title %></h3>
      <small>
         <%= product.description %>
      </small>
      <br/>
      <strong>$<%= sprintf("%0.2f", product.price) %></strong>
      <%= link_to 'Add to Cart',
                  :action => 'add_to_cart',
                  :id     => product %>
      <br/>
    </td>
  </tr>
 
  <tr><td colspan="2"><hr/></td></tr>
 
<% end %>
</table>

Fairly verbose for simply listing a set of products. In Haml, this is the exact same code:

%table{ :cellpadding => "5", :cellspacing => "0" }
  - for product in @products
  %tr{ :valign => "top" }
    %td
      %img{ :src => product.image_url }
    %td{ :width => "450" }
      %h3= h product.title
      %small= product.description
      %br
      %strong= sprintf("$%0.2f", product.price)
      = link_to 'Add to Cart', :action => 'add_to_cart', :id => product
      %br
  %tr
    %td{ :colspan => "2" }
      %hr
  - end

Let your eyes glaze over it and notice what’s going on. Attributes of elements in hashes. The indentation is the semantics. Throw an equal sign in front of an element and executed ruby code is its content. A minus sign means ruby code is evaluated but not displayed. Gorgeous, yeah?

It takes a little bit of getting used to, and at this version of the project, is about 1.3x slower than straight ERB, but once you start writing code in Haml, it’s a little addictive. There’s infinitely more things Haml (and it’s CSS counterpart, Sass) does. Hate looking up that pesky XHTML 1.1 Doctype? Haml has you covered.

!!! 1.1

Yes, that’s all. Class and ID names of elements are added to an element like thus:

%h1#page_header.title

That H1 element has an ID of ‘page_header’ and a class of ‘title’. Of course you can string additional classes to that, such as ‘.title.list’.

Don’t take my word for it. Hit up Haml’s web site, and be amazed. A site has been put up where you can test out Haml and Sass without the trouble of downloading it.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*