Writing elegant HTML with HAML

January 4, 2012


This post was originally published in the Rambling Labs Blog on January 4, 2012.


Another cool thing that we learned while building the new Rambling Labs site was HAML. It’s a markup language that is based on the premise that ‘Markup should be beautiful’, in their own words.

It’s very easy to install, just add gem 'haml' to your Gemfile and run bundle install. To use it, replace your view_name.html.erb file with a view_name.html.haml file.

Like SASS and CoffeeScript, to achieve the beauty it professes, HAML uses indentation to determine what it should do next. This means, and you guessed it, that it writes beautifully.

Compare this ERb file:

<div id="single_post">
  <h2 class="post_title"><%= link_to post.title, post %></h2>
  <div class="post_content">
    <div class="post_date">
      Posted on <%= post.date.strftime '%e %B %Y' %>
    </div>
    <div class="posted_by">
      By: <%= post.author %>
    </div>
    <div class="comments_number">
      <%= post.comment_count %>
    </div>
    <% if summary %>
      <%= post.summary_html %>
      <%= link_to post do %>
        Continue Reading &raquo;
      <% end %>
    <% else %>
      <%= post.content_html %>
    <% end %>
    <ul class="post_tags">
      <% post.tags.each do |tag| %>
        <li>
          <a href="<%= tag_path(tag) %>">
            <%= tag.name %>
          </a>
        </li>
    </ul>
  </div>
</div>

To this HAML file:

#single_post
  %h2.post_title= link_to post.title, post
  .post_content
    .post_date
      Posted on #{post.date.strftime '%e %B %Y'}
    .posted_by
      By: #{post.author}
    .comments_number= post.comment_count
    - if summary
      = post.summary_html
      = link_to post do
        Continue Reading &raquo;
    - else
      = post.content_html
    %ul.post_tags
      - post.tags.each do |tag|
        %li
          %a{href: "/blog/tag/#{tag.name}"}= tag.name

Just beautiful, right?

Note that the closing tags as well as the closing end keywords are thrown away, by convention the default element is div, in order to execute ruby, the statement is preceeded by -, and to print the result of a ruby statement both the = and the #{} are used.

I just love it!

Nevertheless, for what I’ve read on the web, some people are against using HAML. Some say that ERb is more natural for people crossing between languages, which might be true. Others just don’t see the point of ‘having to learn something more’ (same happens with CoffeeScript). This latter opinion I consider an invalid reason. As a programmer, you should always be challenging yourself, be it within your regular tools or within new ones.

It is true, though, that unlike SASS, HAML and CoffeeScript don’t add functionality that can’t be achieved with ERb and JavaScript, but I don’t think that should be a show stopper. If you think otherwise, be my guest.

Be sure to add this tool to your toolbox!