Trim the fat with HAML

The announcement of Rails 1.2 wasn’t the only interesting post on weblog.rubyonrails.org, I also found out about HAML a templating system for Rails that cleans up your code and banishes those ugly ASP type tags.

If you look at the two partials of a form you’ll see that you not only save a few lines of code (and even more characters), but it’s much more legible and easier to maintain down the road.

<div class=“block”>
    <h2>Details</h2>
    <dl>
        <dt class=“required”><label for=“country_continent_id”>Continent:</label></dt>
        <dd>
            <%= f.collection_select(:continent_id, @continents, :id, :name) %>
        </dd>
        <dt class=“required”><label for=“country_name”>Country:</label></dt>
        <dd>
            <%= f.text_field :name %>
        </dd>
        <dt class=“required”><label for=“country_content”>Content:</label></dt>
        <dd>
            <%= f.text_area :content, :rows=>10 %>
        </dd>
    </dl>
</div>

pre-HAML _form.rhtml

.block
  %h2 Details
  %dl
    %dt.required
      %label{:for => country_continent_id} Continent:
    %dd= f.collection_select(:continent_id, @continents, :id, :name)
    %dt.required
      %label{:for => country_name} Country:
    %dd= f.text_field :name
    %dt.required
      %label{:for => country_content} Content:
    %dd= f.text_area :content, :rows=>10

post-HAML _form.haml

In HAML divs are implicit so you can just type the class name (.block) and it will give you a div for free, tags start with ‘%’ (%p, %table, %h1) and are auto-closed.

HAML installs as a plugin and any .haml files will overide their .rhtml brothers. On the HAML site there’s a great tutorial and reference.

There’s already a TextMate bundle for HAML here.

One Response to “Trim the fat with HAML”

  1. Wesly Says:

    hey there,

    I absolutely LOVE the colour scheme you use for the syntax highlighting above.. Do you happen to have a Scintilla.NET XML file which holds those colours? Or do you have an easy accessible file for those colours. I’d love to use them during development!

    Thanks!

    Wes

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image