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 Comment

  1. Posted January 26, 2007 at 8:25 am | Permalink

    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

Post a Comment

Your email is never shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word