HAML (HTML Abstraction Markup Language) is a template engine responsible for addressing many of the flaws in traditional markup. HAML is Whitespace Active, DRY, follows CSS Conventions, and integrates Ruby or PHP code. Its results in very clean and elegant markup.
I will be focusing on the Ruby implementation in this posting, but note that there are also implementations for PHP, .NET, Java, and several other languages. As you might expect with Ruby, HAML is installed as a gem, and once installed, all .erb files can be renamed .HAML to be run through the HAML compiler.
When using HAML, tags are marked with the % symbol. For example:
%strong hello
This would be compiled to:
<strong>hello<strong>
Although you could write:
%div hello
to create a div, it is not necessary as HAML makes the common div tag the default. It also borrows the period symbol from CSS to denote class, so the following:
.content Hi
would be compiled to:
<div class='content'></div>
Classes can also be chained, so the following:
.content.notice Bye
would be compiled to:
<div class='content notice'>Bye</div>
HAML is whitespace active, so we can nest divs as follows:
#parent
#child
#grandchild
#brother-twin I am the evil twin
#sister-twin I am the good twin
to create:
<div id="parent">
<div id="child">
<div id="grandchild">
<div id="brother-twin">I am the evil twin</div>
<div id="sister-twin"> I am the good twin</div>
</div>
</div>
</div>
Comments are also more legible in HAML:
/ here is a comment
would generate the bulkier:
<!-- here is a comment -->
HAML includes filters which are denoted by a colon, and some examples are
:plain :javascript :markdown
You can also create your own. Usage is simple:
#content
:markdown
Some *emphasis*
would compile to:
<div id="content"> <p>Some <em>emphasis</em></p> </div>
Including Ruby (or other) code is either silent with the dash symbol, or inline with the equals symbol.
#content
.title
%h1=@title
would create:
<div id="content">
<div class="title">
<h1>My Page</h1>
</div>
</div>
One of my favorites is the Object Reference, which uses square brackets with an object. Basically, given an object, it will work as div_for and content_for in Ruby, generating a id and class name based on the id and class of the given object. This is very handy for use with javascript and jquery and really polishes the markup.
%div[monster]
%ul.eyeballs
-monster.eyeballs.each do |eyeball|
%li[eyeball]
=eyeball.color
would create:
<div id="monster_4">
<ul>
<li id="eyeball_1">Green</li>
<li id="eyeball_2">Blue</li>
<li id="eyeball_3">Grey</li>
</ul>
</div>


