Jump To Content

LearnHub




Using Haml

An introduction to haml

haml is template languages for Ruby on Rails. It's a plugin that provides an alternative to Rails' native view templating library erb. sass is included with haml, and provides templating for css files. Through clever usage of whitespace, both remove much of the verbosity of html and css (<>, end tags ,etc) , providing a concise way of creating templates. For example, take this typical layout template:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
 <title><%= controller.action_name %></title>
 <%= stylesheet_link_tag 'mycss' %>
</head>
  <body>
   <p style="color: green">
     <%= flash[:notice] %>
   </p>
   <div id="header">
     <h1>Header</h1>
   </div>
   <div id="content">
     <%= yield %>
   </div>
  </body>
</html>

Here's the same thing in haml. Notice the usage of whitespace to delimit block the nesting of the code. Also, regular html can be mixed in as well.


!!!
%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}
  %head
    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
    %title= controller.action_name
    = stylesheet_link_tag 'mycss'
  %body
    %p{:style => "color:green"}= flash[:notice]
    #header
      %h1 Header
    #content
      = yield
There are a few benefits to this:
  • the information density is greater, so more of the template is visible on screen.
  • less characters to type, so less chance to make a typo
  • nesting is clearly visible, and no more issues with missing end tags.

  1. Andrew Brown saidThu, 17 Apr 2008 13:22:42 -0000 ( Link )

    So much cleaner. 5 mins in and it felt natural
    Converted one of my Rails apps over to it.

    Actions
    Vote
    Current Rating
    1
    Rate Up
    Rate Down
    1 Total Vote

    Post Comments

  2. Andrew Brown saidFri, 18 Apr 2008 17:23:49 -0000 ( Link )

    Also probably good idea to also pick up the rspec-haml-scaffold-generator plugin

    Actions
    Vote
    Current Rating
    1
    Rate Up
    Rate Down
    1 Total Vote

    Post Comments

  3. Carsten saidFri, 18 Apr 2008 17:39:51 -0000 ( Link )

    Also to note, there are a couple TextMate bundles that are quite handy when using Haml & Sass:

    And remember to use Soft Tabs set to 2 spaces when editing Haml or Sass files.

    Actions
    Vote
    Current Rating
    1
    Rate Up
    Rate Down
    1 Total Vote

    Post Comments

  4. Andrew Brown saidFri, 18 Apr 2008 17:58:20 -0000 ( Link )

    Changing Tab Size is down below

    And seeing if you have any nasty hard tabs hiding

    Actions
    Vote
    Current Rating
    1
    Rate Up
    Rate Down
    1 Total Vote

    Post Comments

Your Comment
Textile is Enabled (View Reference)