HAML Tutorial

By Xah Lee. Date: . Last updated: .

What is Haml

Haml Logo

haml logo
Haml logo (2014)
Haml 1-5 logo
old haml logo. (~2006 to 2013)

Sample Haml Code

!!!
%html{ :xmlns => "http://www.w3.org/1999/xhtml", :lang => "en", "xml:lang" => "en"}
  %head
    %title BoBlog
    %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}
    %link{"rel" => "stylesheet", "href" => "main.css", "type" => "text/css"}
  %body
    #header
      %h1 BoBlog
      %h2 Bob's Blog
    #content
      - @entries.each do |entry|
        .entry
          %h3.title= entry.title
          %p.date= entry.posted.strftime("%A, %B %d, %Y")
          %p.body= entry.body
    #footer
      %p
        All content copyright © Bob

The above haml file generates this XHTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <title>BoBlog</title>
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
    <link href="/stylesheets/main.css" media="screen" rel="Stylesheet" type="text/css" />
  </head>
  <body>
    <div id='header'>
      <h1>BoBlog</h1>
      <h2>Bob's Blog</h2>
    </div>
    <div id='content'>
      <div class='entry'>
        <h3 class='title'>Halloween</h3>
        <p class='date'>Tuesday, October 31, 2006</p>
        <p class='body'>
          Happy Halloween, glorious readers! I'm going to a party this evening... I'm very excited.
        </p>
      </div>
      <div class='entry'>
        <h3 class='title'>New Rails Templating Engine</h3>
        <p class='date'>Friday, August 11, 2006</p>
        <p class='body'>
          There's a very cool new Templating Engine out for Ruby on Rails. It's called Haml.
        </p>
      </div>
    </div>
    <div id='footer'>
      <p>
        All content copyright © Bob
      </p>
    </div>
  </body>
</html>

Installing Haml

on Ubuntu linux:

# install haml
sudo gem install haml

By default, it installs at /usr/local/bin/haml

Haml Syntax Basics

haml --help
Basic doc.
haml --version
Show version

There are 2 classes of haml syntax. One is “static”, one is “dynamic”. Static ones simply convert text to HTML. Dynamic ones are those contain ruby/python etc code that generates output, or set variables, etc.

The following are static syntax. They are simple transformations.

The following are dynamic syntax. They are templates to evaluate code.

!!! Strict
Doctype
!!! XML
Xml doctype

more stuff

%strong=code

%strong{:class => "xyz", :id => "abc"} all rabbits

<strong class="xyz" id="abc">all rabbits</strong>

.xyz some water

<div class='xyz'>some water</div>

.item{:id => "item#{code1}"}= code2

<div class='item' id='item‹code1 output›'>
‹code2 output›
</div>

.item{:id => "item#{item.id}"}= item.body

<div class='item' id='item<%= item.id %>'>
  <%= item.body %>
</div>