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,

!!! 5
%html   %head     %title my title   %body     #main       %span#my-span my content

This would render as:

<!DOCTYPE html>
<html>
  <head>
    <title>my title</title>
  </head>
  <body>
    <div id='main'>
      <span id='my-span'>my content</span>
    </div>
  </body>
</html>

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
%body
%div
 
<body></body>
<div></div>

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

This Haml code   Renders as
%span
  content
 
<span>
  content
</span>

Or by entering a space,

This Haml code   Renders as
%span content
 
<span>content</span>

HTML tags are passed unmodified

This Haml code   Renders as
<html>
%body </html>
 
<html>
<body></body>
</html>

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

You can use the Ruby hash notation:

This Haml code
%link{:rel => 'stylesheet', :type => 'text/css', :href => '/css/styles.css'}
 
Renders as
<link href='/css/styles.css' rel='stylesheet' type='text/css' />

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

This Haml code
%link(rel='stylesheet' type='text/css' href='/css/styles.css')
 
Renders as
<link href='/css/styles.css' rel='stylesheet' type='text/css' />

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
#container
  %span.red text here
 
<div id='container'>
  <span class='red'>text here</span>
</div>

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
%div#container
#container
 
<div id='container'></div>
<div id='container'></div>

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

This Haml code
!!!
!!! Strict
!!! 5
 
Renders as
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html>