Learning to Use Haml

What is Haml?

Haml is an abstraction markup language, a layer on top of HTML. It’s a way of writing more beautiful and faster markup.

With Haml,

  • You avoid writing redundant code, like closing tags.
  • You leverage your knowledge of CSS selectors.
  • You write views faster.

Haml by Example

Now let’s look at an example of a basic structure,

This would render as:

Whitespace is important to Haml, but it doesn’t matter if you use blanks or tabs as long as you’re consistent (me, I’m more of a space-guy).

Use % to create a tag,

This Haml code   Renders as
 

You can add content to an element by indenting a level below,

This Haml code   Renders as
 

Or by entering a space,

This Haml code   Renders as
 

HTML tags are passed unmodified

This Haml code   Renders as
 

There are two ways of adding attributes: {} or ()

You can use the Ruby hash notation:

This Haml code
 
Renders as

Or the parens notation, which is more HTML-ish:

This Haml code
 
Renders as

There’s a shortcut, using CSS selector syntax, for including IDs and/or classes to an element. As in CSS, use the # character for the ID and the dot for a class:

This Haml code   Renders as
 

As you can see the <div> element is implied when no tag was specified. These two lines would render the same:

This Haml code   Renders as
 

For the Web Standardistas, Haml provides pretty much any DOCTYPE you’d need:

This Haml code
 
Renders as
Focus Mode

Contact Request

Close

We will call you right away. All information is kept private