Desk2Mob

Desk2Mob

Desk2Mob

HAML

Meaning: HTML Abstraction Markup Language

HAML – HTML Abstraction Markup Language

When working with Ruby on Rails (or even standalone Ruby projects), developers often look for cleaner, more concise ways to write HTML templates. One of the popular alternatives to traditional .erb templating is HAML — the HTML Abstraction Markup Language.

HAML eliminates the need for explicit closing tags and reduces repetitive boilerplate, leading to code that is both easier to read and maintain. It enforces indentation-based structure (similar to Python), making the template visually represent the hierarchy of the HTML document.

Why HAML?

  • Cleaner syntax: No need for <div>, </div>, or closing tags everywhere.
  • Less boilerplate: Reduces redundant markup, especially with nested structures.
  • Ruby integration: Embedded Ruby fits naturally into HAML templates.
  • Readable structure: The indentation shows DOM hierarchy clearly.

A Quick Comparison

Here’s a simple Rails view written in ERB:


    <div class="my-container">
      <h1>Welcome to My Blog</h1>
      <p>Hello, <%= @user.name %>!</p>
      <ul>
        <% @posts.each do |post| %>
          <li>
          <a href="<%= postpath(post) %>"><%= post.title %></a>
          </li>
        <% end %>
      </ul>
    </div>
  

The equivalent HAML template looks like this:


    .my-container
    %h1 Welcome to My Blog
    %p Hello, #{@user.name}!
    %ul
      - @posts.each do |post|
        %li
          = linkto post.title, post_path(post)
  

Notice the differences:

  • No closing tags (</div> or </ul>).
  • Indentation defines the hierarchy.
  • Ruby code is embedded more naturally (- for control flow,= for output).

Getting Started with HAML in Rails

  • Add HAML gem to your Rails project:

    
            #Gemfile
            gem 'haml-rails'
          
  • Run bundle install.

  • Convert your .erb templates to .haml (you can use the html2haml gem to assist with this).
  • Start writing templates in clean, readable HAML.

Final Thoughts

HAML brings elegance to view templates in Rails applications by reducing boilerplate and making markup more intuitive. While ERB remains the default, many developers prefer HAML for its readability and developer-friendly syntax.

If you enjoy cleaner, indentation-based markup, give HAML a try in your next Rails project!

Added on August 28, 2025 by Amit Pandya in Ruby On Rails


All Abbreviations