Why HAML?

Haml (HTML abstraction markup language) is based on one primary principle: markup should be beautiful. It’s not just beauty for beauty’s sake either; Haml accelerates and simplifies template creation down to veritable haiku.

Why do we use HAML?
- Mark up should be beautiful.
- Mark up should be Dry (Because Too much repetition in HTML and template engines like ERB).
- Mark up should be well-indented.
- Mark up structure should be clear.
- Haml to the rescue:

In HTML
1
2
3
4
5
6
7
<ul id="navigation">
 <li class="menu_item">
   <a href="/home" title="Home">
     Home
   </a>
 </li>
</ul>
In HAML
1
2
3
4
%ul#naviatioin
  %li.menu_item
    %a{:href => "/home", :title => "Home"}
      Home

HAML Basic
Syntax:

In HAML
1
2
3
4
5
6
7
8
9
10
!!!
%html
  %head
    %title Haml Test
  %body
    #header
      %h1 Welcome to my blog
      %nav#navigation
    #content
      #yield

Format:
- HTML Tags are prefixed with ” % ”
- ID attributes are prefixed with ” # ”
- Class attributes are prefixed with ” . ”
- Additional attributes are passed as: %a{:title => “Home”, :href => “/home”} Home

HAML Formatting
Remove “ < ” and “ > ”

In HTML
1
2
3
4
<img />
<p>
  Hello Haml
</p>

In HAML
1
2
3
%img
%p
  Hello Haml

Dynamic HAML
– We use the “ = ” sign to evaluate dynamic code and assign the value to the desired tag.
– We use the “ – ” sign to run code without appending a value to any tag.
– We use Ruby interpolation to mix static and dynamic strings.

In HAML
1
2
3
4
5
6
%h2= "posts for #{Time.now}"
%ul#posts
 @posts.each do |post|
  %li.post_item
    %h3= post.title
    %p= post.post

For more information haml.info