Thursday, May 1, 2008

haml

Many have heard of and started using haml already, but since this is my list for 5 tips for rails, I cannot leave this out.

It is very simple to install and use haml, like most things ruby and/or/on rails. There are a couple of things that took me a few minutes that I would like to show quickly.

  • To install the haml gem:
    sudo gem install haml
  • Get it working on your rails project after installing the gem:

    cd /path/to/rails_project
    haml --rails .

Here is a quick haml demo to create the layout


!!! XML
!!! STRICT
%html
{html_attrs}
%head
%title
Application:
=controller.action_name
%body
-if is_admin?
You are admin
%br{:clear => 'all'}

#main
=yield


Some things to note:
  • erb uses <%= ... %> and <%- ... %> haml just uses = and - respectively.
  • haml does NOT use end tags of any kind, it only looks at the spacing/tabs (tab = 2 spaces, and yes you must use spaces). This is easily seen with the if statement. the yield is not part of the if block because it is aligned with the if, not tabbed under it.
  • The braces beside a %tag, for instance with %b, constitue a hash that allows you to set the properties of the tag. You can set styles, ids, or anything else you want
  • #name creates a div with id = name
  • .name create a class with id = name


Why is this cool? It is faster to write, easier to for designers to look at it. Furthermore, erb will not tab the views inside of a layout or partials inside of a view to line up with the rest of the document. Haml does, and this make it so much easier to look at the read.

for more on haml go to http://haml.hamptoncatlin.com

0 comments: