Skip to content

Instantly share code, notes, and snippets.

@trek
Created May 9, 2009 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trek/109326 to your computer and use it in GitHub Desktop.
Save trek/109326 to your computer and use it in GitHub Desktop.

Haml, an HTML shorthand.

Tags

Haml uses the percent sign (%) to indicate an HTML tag.

%p
%div
%strong
%link

becomes

<p></p>
<div></div>
<strong></strong>
<link/>

Content inside a Tag

Content goes one line below the tag, indented two spaces.

%p 
  Hello, I am a paragraph.
%div 
  Oh, hai, I'm a div.

Tags inside other Tags

Content can be plain text or another tag.

%p 
  Hello, I am a paragraph.
  %div 
    Oh, hai, I'm a div inside of that paragraph

becomes

<p> 
  Hello, I am a paragraph.
  <div> 
    Oh, hai, I'm a div inside of that paragraph
  </div>
</p>

Attributes

Haml uses the following syntax for HTML Tag Attributes

%tag{:attribute_a => 'the value of a', :attribute_b => 'the value of b'}

so

%form{:action => '/url/where/we/send/data', :method => 'post'}
  %input{:type => 'text', :name => 'first_name'}
  %button send!

becomes

<form action='/url/where/we/send/data' method='post'>
  <input type='text' name='first_name' />
  <button>send!</button>
</form>

id and class, the most common attributes

Haml has a shortcut for the most common attributes you're likely to use: id and class. You can add them in the normal attribute way

%p{:id => 'breadcrumbs', :class => 'navigation'}

or using this css-like notation

%p#breadcrumbs.navigation

both are equivalent to

<p id='breadcrumbs' class='navigation'></p>

You can combine both methods at once

%div#header.navigation{:class => 'current'}

becomes

<div class='current navigation' id='header'></div>

<div>, the most common Tag

Haml has a shortcut for the <div> tags with classes and ids, since this is the most common structural HTML.

%div.navigation#header

and

.navigation#header

both become

<div id='header' class='navigation'></div>

All Together Now

You'll see us write 104 character examples like this:

%html
  %body
    #hd
    #bd
      #navigation
        %ul
          %li.current home
          %li login
      %p#leader blah, blah, blah
      %p blah, blah blah
    #ft

Instead of 219 character examples like this:

<html>
  <body>
    <div id='hd'></div>
    <div id='bd'>
      <div id='navigation'>
        <ul>
          <li class='current'>home</li>
          <li>login</li>
        </ul>
      </div>
      <p id='leader'>blah, blah, blah</p>
      <p>blah, blah blah</p>
    </div>
    <div id='ft'></div>
  </body>
</html>

Savings

Haml lets us explain concepts in 50% the space, in 50% the time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment