Vixiom Axioms

January 22, 2007

Trim the fat with HAML

Filed under: Ruby on Rails Alastair @ 9:02 am

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.

Digg! submit Trim the fat with HAML to stumbleupon.com submit Trim the fat with HAML to del.icio.us submit Trim the fat with HAML to reddit.com Like this post? subscribe to the feed.

1 Comment »

  1. 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

    Comment by Wesly — January 26, 2007 @ 8:25 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

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

Powered by WordPress